How to use nodeStream method in Playwright Internal

Best JavaScript code snippet using playwright-internal

streams.js

Source:streams.js Github

copy

Full Screen

1/**2 * Streams3 * Pokemon Showdown - http://pokemonshowdown.com/4 *5 * The Node.js standard library's Streams are really hard to use. This6 * offers a better stream API.7 *8 * Documented in STREAMS.md.9 *10 * @license MIT11 */12'use strict';13const BUF_SIZE = 65536 * 4;14class ReadStream {15 /** @param {{[k: string]: any} | NodeJS.ReadableStream | string | Buffer} optionsOrStreamLike */16 constructor(optionsOrStreamLike = {}) {17 this.buf = Buffer.allocUnsafe(BUF_SIZE);18 this.bufStart = 0;19 this.bufEnd = 0;20 this.bufCapacity = BUF_SIZE;21 // TypeScript bug: can't infer type22 /** @type {number} */23 this.readSize = 0;24 this.atEOF = false;25 this.encoding = 'utf8';26 /** @type {true} */27 this.isReadable = true;28 this.isWritable = false;29 /** @type {NodeJS.ReadableStream?} */30 this.nodeReadableStream = null;31 /** @type {(() => void)?} */32 this.nextPushResolver = null;33 /** @type {Promise<void>} */34 this.nextPush = new Promise(resolve => {35 this.nextPushResolver = resolve;36 });37 this.awaitingPush = false;38 let options;39 if (typeof optionsOrStreamLike === 'string') {40 options = {buffer: optionsOrStreamLike};41 } else if (optionsOrStreamLike instanceof Buffer) {42 options = {buffer: optionsOrStreamLike};43 } else if (typeof /** @type {any} */ (optionsOrStreamLike)._readableState === 'object') {44 options = {nodeStream: /** @type {NodeJS.ReadableStream} */ (optionsOrStreamLike)};45 } else {46 options = optionsOrStreamLike;47 }48 if (options.nodeStream) {49 const nodeStream = /** @type {NodeJS.ReadableStream} */ (options.nodeStream);50 this.nodeReadableStream = nodeStream;51 nodeStream.on('data', data => {52 this.push(data);53 });54 nodeStream.on('end', () => {55 this.push(null);56 });57 /**58 * @this {ReadStream}59 * @param {number} bytes60 */61 options.read = function (bytes) {62 this.nodeReadableStream.resume();63 };64 /**65 * @this {ReadStream}66 * @param {number} bytes67 */68 options.pause = function (bytes) {69 this.nodeReadableStream.pause();70 };71 }72 if (options.read) this._read = options.read;73 if (options.pause) this._pause = options.pause;74 if (options.destroy) this._destroy = options.read;75 if (options.encoding) this.encoding = options.encoding;76 if (options.buffer !== undefined) {77 this.push(options.buffer);78 this.push(null);79 }80 }81 get bufSize() {82 return this.bufEnd - this.bufStart;83 }84 moveBuf() {85 if (this.bufStart !== this.bufEnd) {86 this.buf.copy(this.buf, 0, this.bufStart, this.bufEnd);87 }88 this.bufEnd -= this.bufStart;89 this.bufStart = 0;90 }91 expandBuf(newCapacity = this.bufCapacity * 2) {92 const newBuf = Buffer.allocUnsafe(newCapacity);93 this.buf.copy(newBuf, 0, this.bufStart, this.bufEnd);94 this.bufEnd -= this.bufStart;95 this.bufStart = 0;96 this.buf = newBuf;97 }98 /**99 * @param {number} additionalCapacity100 */101 ensureCapacity(additionalCapacity) {102 if (this.bufEnd + additionalCapacity <= this.bufCapacity) return;103 const capacity = this.bufEnd - this.bufStart + additionalCapacity;104 if (capacity <= this.bufCapacity) {105 return this.moveBuf();106 }107 let newCapacity = this.bufCapacity * 2;108 while (newCapacity < capacity) newCapacity *= 2;109 this.expandBuf(newCapacity);110 }111 /**112 * @param {Buffer | string | null} buf113 */114 push(buf, encoding = this.encoding) {115 let size;116 if (this.atEOF) return;117 if (buf === null) {118 this.atEOF = true;119 this.resolvePush();120 return;121 } else if (typeof buf === 'string') {122 size = Buffer.byteLength(buf, encoding);123 this.ensureCapacity(size);124 this.buf.write(buf, this.bufEnd);125 } else {126 size = buf.length;127 this.ensureCapacity(size);128 buf.copy(this.buf, this.bufEnd);129 }130 this.bufEnd += size;131 if (this.bufSize > this.readSize && size * 2 < this.bufSize) this._pause();132 this.resolvePush();133 }134 resolvePush() {135 if (!this.nextPushResolver) throw new Error(`Push after end of read stream`);136 this.nextPushResolver();137 if (this.atEOF) {138 this.nextPushResolver = null;139 return;140 }141 this.nextPush = new Promise(resolve => {142 this.nextPushResolver = resolve;143 });144 }145 /**146 * @param {number} [size]147 * @return {void | Promise<void>}148 */149 _read(size = 0) {150 throw new Error(`ReadStream needs to be subclassed and the _read function needs to be implemented.`);151 }152 _destroy() {}153 _pause() {}154 /**155 * @param {number?} byteCount156 */157 async loadIntoBuffer(byteCount = null) {158 if (byteCount === 0) return;159 this.readSize = Math.max(byteCount || (this.bufSize + 1), this.readSize);160 /** @type {number?} */161 let bytes = this.readSize - this.bufSize;162 if (bytes === Infinity || byteCount === null) bytes = null;163 while (!this.atEOF && this.bufSize < this.readSize) {164 if (bytes) this._read(bytes);165 else this._read();166 await this.nextPush;167 }168 }169 /**170 * @param {number?} byteCount171 */172 async peek(byteCount = null, encoding = this.encoding) {173 if (byteCount === null && this.bufSize) return this.buf.toString(encoding, this.bufStart, this.bufEnd);174 await this.loadIntoBuffer(byteCount);175 if (byteCount === null) return this.buf.toString(encoding, this.bufStart, this.bufEnd);176 if (byteCount > this.bufSize) byteCount = this.bufSize;177 if (!this.bufSize) return null;178 return this.buf.toString(encoding, this.bufStart, this.bufStart + byteCount);179 }180 /**181 * @param {number?} byteCount182 */183 async peekBuffer(byteCount = null) {184 if (byteCount === null && this.bufSize) return this.buf.slice(this.bufStart, this.bufEnd);185 await this.loadIntoBuffer(byteCount);186 if (byteCount === null) return this.buf.slice(this.bufStart, this.bufEnd);187 if (byteCount > this.bufSize) byteCount = this.bufSize;188 if (!this.bufSize) return null;189 return this.buf.slice(this.bufStart, this.bufStart + byteCount);190 }191 /**192 * @param {number? | string} byteCount193 */194 async read(byteCount = null, encoding = this.encoding) {195 if (typeof byteCount === 'string') {196 encoding = byteCount;197 byteCount = null;198 }199 const out = await this.peek(byteCount, encoding);200 if (byteCount === null || byteCount >= this.bufSize) {201 this.bufStart = 0;202 this.bufEnd = 0;203 } else {204 this.bufStart += byteCount;205 }206 return out;207 }208 /**209 * @param {number?} byteCount210 */211 async readBuffer(byteCount = null) {212 const out = await this.peekBuffer(byteCount);213 if (byteCount === null || byteCount >= this.bufSize) {214 this.bufStart = 0;215 this.bufEnd = 0;216 } else {217 this.bufStart += byteCount;218 }219 return out;220 }221 /**222 * @param {string} symbol223 */224 async indexOf(symbol, encoding = this.encoding) {225 let idx = this.buf.indexOf(symbol, this.bufStart, encoding);226 while (!this.atEOF && (idx >= this.bufEnd || idx < 0)) {227 await this.loadIntoBuffer();228 idx = this.buf.indexOf(symbol, this.bufStart, encoding);229 }230 if (idx >= this.bufEnd) return -1;231 return idx - this.bufStart;232 }233 async readAll(encoding = this.encoding) {234 return (await this.read(Infinity, encoding)) || '';235 }236 peekAll(encoding = this.encoding) {237 return this.peek(Infinity, encoding);238 }239 /**240 * @param {string} symbol241 */242 async readDelimitedBy(symbol, encoding = this.encoding) {243 if (this.atEOF && !this.bufSize) return null;244 const idx = await this.indexOf(symbol, encoding);245 if (idx < 0) {246 return this.readAll(encoding);247 } else {248 const out = await this.read(idx, encoding);249 this.bufStart += Buffer.byteLength(symbol, 'utf8');250 return out;251 }252 }253 async readLine(encoding = this.encoding) {254 if (!encoding) throw new Error(`readLine must have an encoding`);255 let line = await this.readDelimitedBy('\n', encoding);256 if (line && line.endsWith('\r')) line = line.slice(0, -1);257 return line;258 }259 async destroy() {260 this.atEOF = true;261 this.bufStart = 0;262 this.bufEnd = 0;263 if (this.nextPushResolver) this.resolvePush();264 return this._destroy();265 }266 /**267 * @param {string | number | null} [byteCount]268 */269 async next(byteCount = null) {270 const value = await this.read(byteCount);271 return {value, done: value === null};272 }273 /**274 * @param {WriteStream} outStream275 * @param {{noEnd?: boolean}} [options]276 */277 async pipeTo(outStream, options = {}) {278 let value, done;279 while (({value, done} = await this.next(), !done)) {280 await outStream.write(value);281 }282 if (!options.noEnd) outStream.end();283 }284}285class WriteStream {286 /**287 * @param {{_writableState?: any, nodeStream?: NodeJS.ReadableStream, write?: (this: WriteStream, data: string | Buffer) => (Promise<any> | undefined), end?: () => Promise<any>}} options288 */289 constructor(options = {}) {290 this.isReadable = false;291 /** @type {true} */292 this.isWritable = true;293 this.encoding = 'utf8';294 /** @type {NodeJS.ReadableStream?} */295 this.nodeWritableStream = null;296 /** @type {(() => void)[]} */297 this.drainListeners = [];298 if (options._writableState) {299 // @ts-ignore300 options = {nodeStream: options};301 }302 if (options.nodeStream) {303 const nodeStream = /** @type {NodeJS.ReadableStream} */ (options.nodeStream);304 this.nodeWritableStream = nodeStream;305 /**306 * @this {WriteStream}307 * @param {string | Buffer} data308 */309 // @ts-ignore TypeScript bug310 options.write = function (data) {311 // @ts-ignore312 const result = this.nodeWritableStream.write(data);313 if (result !== false) return undefined;314 if (!this.drainListeners.length) {315 // @ts-ignore316 this.nodeWritableStream.once('drain', () => {317 for (const listener of this.drainListeners) listener();318 this.drainListeners = [];319 });320 }321 return new Promise(resolve => {322 this.drainListeners.push(resolve);323 });324 };325 options.end = function () {326 return new Promise(resolve => {327 // @ts-ignore328 this.nodeWritableStream.end(() => resolve());329 });330 };331 }332 if (options.write) this._write = options.write;333 if (options.end) this._end = options.end;334 }335 /**336 * @param {Buffer | string | null} chunk337 * @return {Promise<boolean>}338 */339 async write(chunk) {340 if (chunk === null) {341 await this.end();342 return false;343 }344 await this._write(chunk);345 return true;346 }347 /**348 * @param {string | null} chunk349 * @return {Promise<boolean>}350 */351 async writeLine(chunk) {352 if (chunk === null) {353 await this.end();354 return false;355 }356 return this.write(chunk + '\n');357 }358 /**359 * @param {Buffer | string} chunk360 * @return {void | Promise<void>}361 */362 _write(chunk) {363 throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`);364 }365 /** @return {void | Promise<void>} */366 _end() {}367 /**368 * @param {string | null} chunk369 * @return {Promise<void>}370 */371 async end(chunk = null) {372 if (chunk) {373 await this.write(chunk);374 }375 return this._end();376 }377}378class ReadWriteStream extends ReadStream {379 constructor(options = {}) {380 super(options);381 /** @type {true} */382 this.isReadable = true;383 /** @type {true} */384 this.isWritable = true;385 }386 /**387 * @param {Buffer | string} chunk388 * @return {Promise<void> | void}389 */390 write(chunk) {391 return this._write(chunk);392 }393 /**394 * @param {string} chunk395 * @return {Promise<void> | void}396 */397 writeLine(chunk) {398 return this.write(chunk + '\n');399 }400 /**401 * @param {Buffer | string} chunk402 * @return {Promise<void> | void}403 */404 _write(chunk) {405 throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`);406 }407 /**408 * In a ReadWriteStream, _read does not need to be implemented409 */410 _read() {}411 /** @return {void | Promise<void>} */412 _end() {}413 async end() {414 return this._end();415 }416}417class ObjectReadStream {418 /**419 * @param {{[k: string]: any} | NodeJS.ReadableStream | any[]} optionsOrStreamLike420 */421 constructor(optionsOrStreamLike = {}) {422 /** @type {any[]} */423 this.buf = [];424 // TypeScript bug: can't infer type425 /** @type {number} */426 this.readSize = 0;427 this.atEOF = false;428 /** @type {true} */429 this.isReadable = true;430 this.isWritable = false;431 /** @type {NodeJS.ReadableStream?} */432 this.nodeReadableStream = null;433 /** @type {(() => void)?} */434 this.nextPushResolver = null;435 /** @type {Promise<void>} */436 this.nextPush = new Promise(resolve => {437 this.nextPushResolver = resolve;438 });439 this.awaitingPush = false;440 let options;441 if (Array.isArray(optionsOrStreamLike)) {442 options = {buffer: optionsOrStreamLike};443 } else if (typeof /** @type {any} */ (optionsOrStreamLike)._readableState === 'object') {444 options = {nodeStream: /** @type {NodeJS.ReadableStream} */ (optionsOrStreamLike)};445 } else {446 options = optionsOrStreamLike;447 }448 if (options.nodeStream) {449 const nodeStream = /** @type {NodeJS.ReadableStream} */ (options.nodeStream);450 this.nodeReadableStream = nodeStream;451 nodeStream.on('data', data => {452 this.push(data);453 });454 nodeStream.on('end', () => {455 this.push(null);456 });457 /**458 * @this {ReadStream}459 * @param {number} bytes460 */461 options.read = function (bytes) {462 this.nodeReadableStream.resume();463 };464 /**465 * @this {ReadStream}466 * @param {number} bytes467 */468 options.pause = function (bytes) {469 this.nodeReadableStream.pause();470 };471 }472 if (options.read) this._read = options.read;473 if (options.pause) this._pause = options.pause;474 if (options.destroy) this._destroy = options.read;475 if (options.buffer !== undefined) {476 this.buf = options.buffer.slice();477 this.push(null);478 }479 }480 /**481 * @param {any} elem482 */483 push(elem) {484 if (this.atEOF) return;485 if (elem === null) {486 this.atEOF = true;487 this.resolvePush();488 return;489 } else {490 this.buf.push(elem);491 }492 if (this.buf.length > this.readSize && this.buf.length >= 16) this._pause();493 this.resolvePush();494 }495 resolvePush() {496 if (!this.nextPushResolver) throw new Error(`Push after end of read stream`);497 this.nextPushResolver();498 if (this.atEOF) {499 this.nextPushResolver = null;500 return;501 }502 this.nextPush = new Promise(resolve => {503 this.nextPushResolver = resolve;504 });505 }506 /**507 * @param {number} [size]508 * @return {void | Promise<void>}509 */510 _read(size = 0) {511 throw new Error(`ReadStream needs to be subclassed and the _read function needs to be implemented.`);512 }513 _destroy() {}514 _pause() {}515 /**516 * @param {number} count517 */518 async loadIntoBuffer(count = 1) {519 if (this.buf.length >= count) return;520 this.readSize = Math.max(count, this.readSize);521 while (!this.atEOF && this.buf.length < this.readSize) {522 let readResult = this._read();523 // @ts-ignore524 if (readResult && readResult.then) {525 await readResult;526 } else {527 await this.nextPush;528 }529 }530 }531 async peek() {532 if (this.buf.length) return this.buf[0];533 await this.loadIntoBuffer();534 return this.buf[0];535 }536 async read() {537 if (this.buf.length) return this.buf.shift();538 await this.loadIntoBuffer();539 if (!this.buf.length) return null;540 return this.buf.shift();541 }542 /**543 * @param {number?} [count]544 */545 async peekArray(count = null) {546 await this.loadIntoBuffer(count || 1);547 if (count === null || count === Infinity) {548 return this.buf.slice();549 }550 return this.buf.slice(0, count);551 }552 /**553 * @param {number?} [count]554 */555 async readArray(count = null) {556 let out = await this.peekArray(count);557 this.buf = this.buf.slice(out.length);558 return out;559 }560 async readAll() {561 await this.loadIntoBuffer(Infinity);562 let out = this.buf;563 this.buf = [];564 return out;565 }566 async peekAll() {567 await this.loadIntoBuffer(Infinity);568 return this.buf.slice();569 }570 async destroy() {571 this.atEOF = true;572 this.buf = [];573 this.resolvePush();574 return this._destroy();575 }576 async next() {577 const value = await this.read();578 return {value, done: value === null};579 }580 /**581 * @param {WriteStream} outStream582 * @param {{noEnd?: boolean}} options583 */584 async pipeTo(outStream, options = {}) {585 let value, done;586 while (({value, done} = await this.next(), !done)) {587 await outStream.write(value);588 }589 if (!options.noEnd) outStream.end();590 }591}592/**593 * @template T594 */595class ObjectWriteStream {596 /**597 * @param {{_writableState?: any, nodeStream?: NodeJS.ReadableStream, write?: (this: WriteStream, data: T) => Promise<any> | undefined, end?: () => Promise<any>}} options598 */599 constructor(options = {}) {600 this.isReadable = false;601 /** @type {true} */602 this.isWritable = true;603 /** @type {NodeJS.ReadableStream?} */604 this.nodeWritableStream = null;605 if (options._writableState) {606 // @ts-ignore607 options = {nodeStream: options};608 }609 if (options.nodeStream) {610 const nodeStream = /** @type {NodeJS.ReadableStream} */ (options.nodeStream);611 this.nodeWritableStream = nodeStream;612 /**613 * @this {WriteStream}614 * @param {T} data615 */616 options.write = function (data) {617 // @ts-ignore618 const result = this.nodeWritableStream.write(data);619 if (result === false) {620 return new Promise(resolve => {621 // @ts-ignore622 this.nodeWritableStream.once('drain', () => {623 resolve();624 });625 });626 }627 };628 options.end = function () {629 return new Promise(resolve => {630 // @ts-ignore631 this.nodeWritableStream.end(() => resolve());632 });633 };634 }635 if (options.write) this._write = options.write;636 if (options.end) this._end = options.end;637 }638 /**639 * @param {T?} elem640 * @return {Promise<boolean>}641 */642 async write(elem) {643 if (elem === null) {644 await this.end();645 return false;646 }647 await this._write(elem);648 return true;649 }650 /**651 * @param {T} elem652 * @return {void | Promise<void>}653 */654 _write(elem) {655 throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`);656 }657 /** @return {void | Promise<void>} */658 _end() {}659 /**660 * @param {T?} elem661 * @return {Promise<void>}662 */663 async end(elem = null) {664 if (elem) {665 await this.write(elem);666 }667 return this._end();668 }669}670class ObjectReadWriteStream extends ObjectReadStream {671 /**672 * @param {{write?: (this: WriteStream, data: string) => Promise<any> | undefined | void, end?: () => Promise<any> | undefined | void}} options673 */674 constructor(options = {}) {675 super(options);676 /** @type {true} */677 this.isReadable = true;678 /** @type {true} */679 this.isWritable = true;680 if (options.write) this._write = options.write;681 if (options.end) this._end = options.end;682 }683 /**684 * @param {any} elem685 * @return {void | Promise<void>}686 */687 write(elem) {688 return this._write(elem);689 }690 /**691 * @param {any} elem692 * @return {void | Promise<void>}693 */694 _write(elem) {695 throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`);696 }697 /**698 * In a ReadWriteStream, _read does not need to be implemented699 */700 _read() {}701 /** @return {void | Promise<void>} */702 _end() {}703 async end() {704 return this._end();705 }706}707module.exports = {708 ReadStream,709 WriteStream,710 ReadWriteStream,711 ObjectReadStream,712 ObjectWriteStream,713 ObjectReadWriteStream,714 /**715 * @param {NodeJS.ReadableStream} nodeStream716 * @param {*} encoding717 */718 readAll(nodeStream, encoding = undefined) {719 return new ReadStream(nodeStream).readAll(encoding);720 },...

Full Screen

Full Screen

stream.js

Source:stream.js Github

copy

Full Screen

...114 );115 generateStreamTest(116 "generateNodeStream(type:nodebuffer / !streamFiles) generates a working stream from other streams", "ref/all.zip",117 function () {118 var helloStream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();119 var imgStream = JSZipTestUtils.createZipAll().file("images/smile.gif").nodeStream();120 var zip = new JSZip();121 zip.file("Hello.txt", helloStream);122 zip.folder("images").file("smile.gif", imgStream);123 return zip;124 },125 {type:'nodebuffer',streamFiles:false}126 );127 generateStreamTest(128 "generateNodeStream(type:nodebuffer / streamFiles) generates a working stream from other streams", "ref/all-stream.zip",129 function () {130 var helloStream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();131 var imgStream = JSZipTestUtils.createZipAll().file("images/smile.gif").nodeStream();132 var zip = new JSZip();133 zip.file("Hello.txt", helloStream);134 zip.folder("images").file("smile.gif", imgStream);135 return zip;136 },137 {type:'nodebuffer',streamFiles:true}138 );139 zipObjectStreamTest("ZipObject#nodeStream generates a working stream[nodebuffer]", function() {140 var zip = JSZipTestUtils.createZipAll();141 return zip.file("Hello.txt").nodeStream('nodebuffer');142 });143 zipObjectStreamTest("ZipObject#nodeStream generates a working stream[default]", function() {144 var zip = JSZipTestUtils.createZipAll();145 return zip.file("Hello.txt").nodeStream();146 });147 test("a ZipObject containing a stream can be read with async", function(assert) {148 var done = assert.async();149 var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();150 var zip = new JSZip();151 zip.file("Hello.txt", stream);152 zip.file("Hello.txt").async("text").then(function(actual) {153 equal(actual, "Hello World\n", "the stream has been read correctly");154 done();155 })['catch'](JSZipTestUtils.assertNoError);156 });157 test("a ZipObject containing a stream can't be read with async 2 times", function(assert) {158 var done = assert.async();159 var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();160 var zip = new JSZip();161 zip.file("Hello.txt", stream);162 // first time, consume the node stream163 zip.file("Hello.txt").async("text");164 // second time, it shouldn't work165 zip.file("Hello.txt").async("text")166 .then(function ok(data) {167 assert.ok(false, "calling 2 times a stream should generate an error");168 done();169 }, function ko(e) {170 assert.ok(e.message.match("has already been used"), "the error message is useful");171 done();172 });173 });174 test("a ZipObject containing a stream can't be read with nodeStream 2 times", function(assert) {175 var done = assert.async();176 var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();177 var zip = new JSZip();178 zip.file("Hello.txt", stream);179 // first time, consume the node stream180 zip.file("Hello.txt").nodeStream().resume();181 // second time, it shouldn't work182 zip.file("Hello.txt").nodeStream()183 .on("error", function (e) {184 assert.ok(e.message.match("has already been used"), "the error message is useful");185 done();186 })187 .on ("end", function () {188 assert.ok(false, "calling 2 times a stream should generate an error");189 done();190 })191 .resume();192 });193 test("generateAsync with a stream can't be read 2 times", function(assert) {194 var done = assert.async();195 var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();196 var zip = new JSZip();197 zip.file("Hello.txt", stream);198 // first time, consume the node stream199 zip.generateAsync({type:"string"});200 // second time, it shouldn't work201 zip.generateAsync({type:"string"})202 .then(function ok(data) {203 assert.ok(false, "calling 2 times a stream should generate an error");204 done();205 }, function ko(e) {206 assert.ok(e.message.match("has already been used"), "the error message is useful");207 done();208 });209 });210 test("generateNodeStream with a stream can't be read 2 times", function(assert) {211 var done = assert.async();212 var stream = JSZipTestUtils.createZipAll().file("Hello.txt").nodeStream();213 var zip = new JSZip();214 zip.file("Hello.txt", stream);215 // first time, consume the node stream216 zip.generateNodeStream().resume();217 // second time, it shouldn't work218 zip.generateNodeStream()219 .on("error", function (e) {220 assert.ok(e.message.match("has already been used"), "the error message is useful");221 done();222 })223 .on ("end", function () {224 assert.ok(false, "calling 2 times a stream should generate an error");225 done();226 })227 .resume();228 });229 test("loadAsync ends with an error when called with a stream", function(assert) {230 var done = assert.async();231 var stream = JSZipTestUtils.createZipAll().generateNodeStream({"type":"nodebuffer"});232 JSZip.loadAsync(stream).then(function () {233 assert.ok(false, "loading a zip file from a stream is impossible");234 done();235 }, function (e) {236 assert.ok(e.message.match("can't accept a stream when loading"), "the error message is useful");237 done();238 });239 });240 } else {241 test("generateNodeStream generates an error", function(assert) {242 try {243 var zip = new JSZip();244 zip.generateNodeStream({type:'nodebuffer',streamFiles:true});245 assert.ok(false, "generateNodeStream should generate an error");246 } catch(err) {247 assert.ok(err.message.match("not supported by this platform"), "the error message is useful");248 }249 });250 test("ZipObject#nodeStream generates an error", function(assert) {251 try {252 var zip = JSZipTestUtils.createZipAll();253 zip.file("Hello.txt").nodeStream('nodebuffer');254 assert.ok(false, "nodeStream should generate an error");255 } catch(err) {256 assert.ok(err.message.match("not supported by this platform"), "the error message is useful");257 }258 });259 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1// pending subscriptions maps a hash of the session id, filename and block id2// to 3var pendingSubscriptions = {},4 subscriptions = {},5 fileBlocks = {};6var sys = require('sys');7// socket.io additions8function subscribe(client, nodeid, ev, type, file, blockIndex, local, sessionId){9 if (!(ev in subscriptions)) subscriptions[ev] = [];10 if (!(ev in client._nodestreamCleanup)) client._nodestreamCleanup[ev] = [];11 client._nodestreamCleanup[ev].push(subscriptions.length);12 subscriptions[ev].push({13 nodeId: nodeid14 , type: type15 , clientId: client.sessionId16 , file: file17 , blockIndex: blockIndex18 , local: local19 , sessionId: sessionId20 });21};22function paint(type, filename, index, local, obj, sessionId){23 var locals = {};24 locals[local] = obj;25 locals._ = {};26 locals.attrs = attrs;27 locals.escape = escape28 // fake a request29 var req = new Request();30 req.sessionId = sessionId;31 var oldSubscribe = req.subscribe;32 // do not resubscribe to append33 req.subscribe = function(file, blockIndex, append, repaint, remove, local){34 return oldSubscribe.call(req, file, blockIndex, '', repaint, remove, local);35 };36 return fileBlocks[filename][index][type].call(req, locals);37};38var Listener = require('socket.io').Listener;39Listener.prototype.nodestream = function(){40 if (!this._nodestream){41 // prevent double-attachment42 this._nodestream = new Nodestream(this);43 }44 return this._nodestream;45};46var Nodestream = function(socket){47 this.socket = socket;48 var self = this;49 socket.on('connection', function(c){50 c.on('message', function(msg){51 if (typeof msg == 'object' && 'nodestream' in msg){52 self._handle(c, msg);53 if (!c._nodestream){54 self._emit('connect', c);55 c._nodestream = true;56 }57 }58 });59 c.on('disconnect', function(){60 if (c._nodestream){61 self._end(c);62 }63 });64 });65};66sys.inherits(Nodestream, process.EventEmitter);67Nodestream.prototype._emit = Nodestream.prototype.emit;68Nodestream.prototype._handle = function(client, message){69 if (!('_nodestreamCleanup' in client)) client._nodestreamCleanup = {};70 // we receive a hash that confirms the suscription of the client71 // to the events stored by that hash72 if (message.subscribe){73 // lookup pending subscriptions by hash74 var subscription = pendingSubscriptions[message.subscribe];75 76 if (subscription){77 if (subscription[2] && subscription[2].length > 1)78 subscribe(client, message.subscribe, subscription[2], 'append', subscription[0], subscription[1], subscription[5], subscription[6]);79 if (subscription[3] && subscription[3].length > 1)80 subscribe(client, message.subscribe, subscription[3], 'repaint', subscription[0], subscription[1], subscription[5], subscription[6]);81 if (subscription[4] && subscription[4].length > 1)82 subscribe(client, message.subscribe, subscription[4], 'remove', subscription[0], subscription[1], null, subscription[6]);83 delete pendingSubscriptions[message.subscribe];84 } else {85 console.error('cant find subscription by encoded id ' + message.subscribe);86 }87 }88};89Nodestream.prototype._end = function(client){90 for (var ev in client._nodestreamCleanup){91 (function(ev){92 client._nodestreamCleanup[ev].forEach(function(i){93 subscriptions[ev][i] = null;94 });95 })(ev);96 }97 this._emit('disconnect', client);98};99Nodestream.prototype.emit = function(ev, obj){100 // notify suscriptors101 var socket = this.socket;102 if (ev in subscriptions){103 subscriptions[ev].forEach(function(s){104 if (!s) return;105 if (socket.clients[s.clientId]){106 var args = {id: s.nodeId};107 108 if (s.type == 'repaint' || s.type == 'append'){109 args.html = paint(s.type, s.file, s.blockIndex, s.local, obj, s.sessionId);110 }111 112 socket.clients[s.clientId].send({113 nodestream: 1,114 type: s.type,115 args: args116 })117 }118 });119 }120};121// express request122var crypto = require('crypto')123 , Request = require('http').IncomingMessage;124function md5(str) {125 return crypto.createHash('md5').update(str).digest('hex');126}127Request.prototype.subscribe = function(file, blockIndex, append, repaint, remove, local){128 if (!('_pendingSubscriptions' in this)){129 this._pendingSubscriptions = {};130 }131 132 var hash = md5(file + blockIndex + this.sessionId + append + repaint + remove)133 , random = md5(hash + Math.random());134 135 if (hash in this._pendingSubscriptions){136 return this._pendingSubscriptions[hash];137 }138 139 pendingSubscriptions[random] = Array.prototype.slice.call(arguments).concat(this.sessionId);140 this._pendingSubscriptions[hash] = random;141 return random;142};143// filters144var jade = require('jade')145 , Compiler = jade.Compiler146 , filters = jade.filters147 , nodes = jade.nodes;148filters.realtime = function(block, compiler, attrs){149 var placeholder, filename = compiler.options.filename;150 151 if (!(filename in fileBlocks)) fileBlocks[filename] = [];152 153 block.forEach(function(node, i){154 if (node.name == 'placeholder'){155 placeholder = new nodes.Tag('div', node.block);156 placeholder.setAttribute('class', '"placeholder"')157 block.splice(i, 1);158 }159 });160 161 if (!attrs.local){162 throw new Error('Please pass the `local` to the :realtime filter options');163 }164 165 if (!attrs.append && !attrs.obj){166 attrs.obj = attrs.local;167 }168 169 var events = ['undefined', attrs.repaint || 'undefined', attrs.remove || 'undefined'];170 171 events.forEach(function(name, i){172 // append '+ obj.id' to events finishing in a dot173 if (/\.'$/.test(name)){174 events[i] = name + (' + ' + (eval(attrs.obj) || 'obj') + '.' + (eval(attrs.id) || 'id'));175 } 176 });177 178 // wrapper tag179 // actually: there's no need to wrap! we could inspect the `class` of the main node, or we could make it an option180 var subscribeString = 'this.subscribe("'+ filename +'", '+ fileBlocks[filename].length + ', ' + events.join(',') + ', '+ (attrs.obj || '"obj"') +')';181 182 block[0].setAttribute('class', block[0].getAttribute('class') + ' + "nodestream nodestream_" + ' + subscribeString);183 block.push(new nodes.Filter('javascript', new nodes.Text('Nodestream.register(\'#{'+ subscribeString +'}\');')));184 185 var compiled = {};186 187 if (attrs.append){188 var bl = new nodes.Block()189 , ifNode = new nodes.Code('if ('+ eval(attrs.local) +'.length)')190 , forEachBlock = new nodes.Block()191 , forEach = new nodes.Each(eval(attrs.local), eval(attrs.obj) || 'obj', undefined, block)192 , elseNode = new nodes.Code('else')193 , elseBlock = new nodes.Block();194 195 forEachBlock.push(forEach);196 ifNode.block = forEachBlock;197 198 if (placeholder){199 elseBlock.push(placeholder);200 elseNode.block = elseBlock;201 }202 203 bl.push(ifNode);204 bl.push(elseNode);205 206 var cc = new Compiler(block);207 compiled['append'] = new Function('locals', 'with (locals) {' + cc.compile() + '}');208 209 // create a fake invisible element that serves as an indicator of where the parent container is210 events = [attrs.append, 'undefined', 'undefined'];211 subscribeString = 'this.subscribe("'+ filename +'", '+ fileBlocks[filename].length + ', ' + events.join(',') + ', '+ (attrs.obj || '"obj"') +')';212 var appendPlaceholder = new nodes.Tag('div');213 appendPlaceholder.setAttribute('class', '"nodestream nodestream_" + ' + subscribeString);214 bl.push(appendPlaceholder);215 bl.push(new nodes.Filter('javascript', new nodes.Text('Nodestream.register(\'#{'+ subscribeString +'}\');')));216 }217 218 if (attrs.repaint){219 var cc = new Compiler(block[0].block);220 compiled['repaint'] = new Function('locals', 'with (locals) {' + cc.compile() + '}');221 }222 223 fileBlocks[filename].push(compiled);224 225 if (attrs.append){226 compiler.visit(bl);227 } else {228 compiler.visit(block);229 }230};231function attrs(obj){232 var buf = [],233 terse = obj.terse;234 delete obj.terse;235 var keys = Object.keys(obj),236 len = keys.length;237 if (len) {238 buf.push('');239 for (var i = 0; i < len; ++i) {240 var key = keys[i],241 val = obj[key];242 if (typeof val === 'boolean' || val === '' || val == null) {243 if (val) {244 terse245 ? buf.push(key)246 : buf.push(key + '="' + key + '"');247 }248 } else {249 buf.push(key + '="' + escape(val) + '"');250 }251 }252 }253 return buf.join(' ');254}255/**256 * Escape the given string of `html`.257 *258 * @param {String} html259 * @return {String}260 * @api private261 */262function escape(html){263 return String(html)264 .replace(/&(?!\w+;)/g, '&amp;')265 .replace(/</g, '&lt;')266 .replace(/>/g, '&gt;')267 .replace(/"/g, '&quot;');...

Full Screen

Full Screen

NodeStream.js

Source:NodeStream.js Github

copy

Full Screen

1/*2 This file is part of LocalRoute.js.3 Copyright (C) 2012, 2013 BusFaster Oy4 LocalRoute.js is free software: you can redistribute it and/or modify it5 under the terms of the GNU Lesser General Public License as published by6 the Free Software Foundation, either version 3 of the License, or7 (at your option) any later version.8 LocalRoute.js is distributed in the hope that it will be useful,9 but WITHOUT ANY WARRANTY; without even the implied warranty of10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11 GNU Lesser General Public License for more details.12 You should have received a copy of the GNU Lesser General Public License13 along with LocalRoute.js. If not, see <http://www.gnu.org/licenses/>.14*/15goog.provide('gis.io.NodeStream');16goog.require('gis.Obj');17goog.require('gis.io.OctetStream');18/** @constructor19 * @extends {gis.io.OctetStream}20 * @param {gis.io.Stream.Endian=} endian21 * @param {NodeBuffer=} data */22gis.io.NodeStream=function(endian,data) {23 gis.io.OctetStream.call(this);24 /** @type {NodeBuffer} */25 this.data=data;26 /** @type {Iconv} */27 this.dec;28 this.setEndian(endian);29};30gis.inherit(gis.io.NodeStream,gis.io.OctetStream);31/** @param {gis.io.Stream.Endian} endian */32gis.io.NodeStream.prototype.setEndian=function(endian) {33 this.endian=endian;34 if(endian==gis.io.Stream.Endian.LITTLE) {35 this.read16=this.read16L;36 this.read32=this.read32L;37 this.readFloat=this.readFloatL;38 this.readDouble=this.readDoubleL;39 } else {40 this.read16=this.read16B;41 this.read32=this.read32B;42 this.readFloat=this.readFloatB;43 this.readDouble=this.readDoubleB;44 }45};46/** @param {string} encoding */47gis.io.NodeStream.prototype.setEncoding=function(encoding) {48 this.encoding=encoding;49 this.dec=new Iconv(encoding,'UTF-8//IGNORE');50};51/** @return {number} */52gis.io.NodeStream.prototype.peek8=function() {53 return(this.data.readUInt8(this.pos));54};55/** @return {number} */56gis.io.NodeStream.prototype.read8=function() {57 return(this.data.readUInt8(this.pos++));58};59/** @return {number} */60gis.io.NodeStream.prototype.read16L=function() {61 return(this.data.readUInt16LE((this.pos+=2)-2));62};63/** @return {number} */64gis.io.NodeStream.prototype.read16B=function() {65 return(this.data.readUInt16BE((this.pos+=2)-2));66};67/** @return {number} */68gis.io.NodeStream.prototype.read32L=function() {69 return(this.data.readUInt32LE((this.pos+=4)-4));70};71/** @return {number} */72gis.io.NodeStream.prototype.read32B=function() {73 return(this.data.readUInt32BE((this.pos+=4)-4));74};75/** @return {number} */76gis.io.NodeStream.prototype.readFloatL=function() {77 return(this.data.readFloatLE((this.pos+=4)-4));78};79/** @return {number} */80gis.io.NodeStream.prototype.readFloatB=function() {81 return(this.data.readFloatLE((this.pos+=4)-4));82};83/** @return {number} */84gis.io.NodeStream.prototype.readDoubleL=function() {85 return(this.data.readDoubleLE((this.pos+=8)-8));86};87/** @return {number} */88gis.io.NodeStream.prototype.readDoubleB=function() {89 return(this.data.readDoubleBE((this.pos+=8)-8));90};91/** @param {number} count92 * @return {string} */93gis.io.NodeStream.prototype.readChars=function(count) {94 var first;95 first=this.pos;96 // Read bytes, convert to UTF8 string and remove trailing ASCII NUL characters.97 return(this.dec.convert(this.data.slice(first,this.pos+=count)).toString('utf8').replace(/[\0]+$/,''));...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1var test = require('tape')2var PassThrough = require('stream').PassThrough3var ReadableStream = require('stream').Readable4var nodeToWebStream = require('.')5test('sanity check', function (t) {6 var str = 'foobar'7 streamToString(nodeToWebStream(stringToStream(str)))8 .then(output => {9 t.equal(str, output)10 t.end()11 })12 .catch(err => t.end(err))13})14test('cancel() ensures cleanup', function (t) {15 t.timeoutAfter(3000)16 var nodeStream = new ReadableStream()17 nodeStream._destroy = function () {18 t.end()19 }20 var webStream = nodeToWebStream(nodeStream)21 nodeStream.on('end', function () {22 })23 webStream.cancel()24})25test('cancel() ensures _destroy()', function (t) {26 t.timeoutAfter(3000)27 var nodeStream = new ReadableStream()28 var webStream = nodeToWebStream(nodeStream)29 nodeStream._destroy = function () {30 t.end()31 }32 webStream.cancel()33})34test('errored node stream', function (t) {35 t.timeoutAfter(3000)36 var nodeStream = new ReadableStream({ read: function () {} })37 var webStream = nodeToWebStream(nodeStream)38 nodeStream.emit('error', new Error('foobar'))39 webStream.getReader().read().catch(function (err) {40 t.equals(err.message, 'foobar')41 t.end()42 })43})44test('node stream closed early', function (t) {45 t.timeoutAfter(3000)46 var nodeStream = new ReadableStream({ read: function () {} })47 var webStream = nodeToWebStream(nodeStream)48 nodeStream.push(null)49 webStream.getReader().read().then(function (result) {50 t.equals(result.done, true)51 t.end()52 })53})54function stringToStream (str) {55 var s = new PassThrough()56 s.end(Buffer.from(str))57 return s58}59function streamToString (stream) {60 return new Promise(function (resolve, reject) {61 let reader = stream.getReader()62 let buffer = ''63 reader.read().then(onRead)64 function onRead (result) {65 if (result.done) return resolve(buffer)66 buffer += result.value.toString()67 reader.read().then(onRead)68 }69 })...

Full Screen

Full Screen

node-to-web-readable-stream.test.js

Source:node-to-web-readable-stream.test.js Github

copy

Full Screen

1var test = require('tape')2var from = require('from2-string')3var ReadableStream = require('readable-stream').Readable4var nodeToWebStream = require('../lib/node-to-web-readable-stream')5test('sanity check', function (t) {6 var str = 'foobar'7 streamToString(nodeToWebStream(from(str)))8 .then(output => {9 t.equal(str, output)10 t.end()11 })12 .catch(err => t.end(err))13})14test('cancel() ensures cleanup', function (t) {15 t.timeoutAfter(3000)16 var nodeStream = from('foobar')17 nodeStream._destroy = function () {18 t.end()19 }20 var webStream = nodeToWebStream(nodeStream)21 nodeStream.on('end', function () {22 })23 webStream.cancel()24})25test('cancel() ensures _destroy()', function (t) {26 t.timeoutAfter(3000)27 var nodeStream = from('foobar')28 var webStream = nodeToWebStream(nodeStream)29 nodeStream._destroy = function () {30 t.end()31 }32 webStream.cancel()33})34test('errored node stream', function (t) {35 t.timeoutAfter(3000)36 var nodeStream = new ReadableStream({ read: function () {} })37 var webStream = nodeToWebStream(nodeStream)38 nodeStream.emit('error', new Error('foobar'))39 webStream.getReader().read().catch(function (err) {40 t.equals(err.message, 'foobar')41 t.end()42 })43})44test('node stream closed early', function (t) {45 t.timeoutAfter(3000)46 var nodeStream = new ReadableStream({ read: function () {} })47 var webStream = nodeToWebStream(nodeStream)48 nodeStream.push(null)49 webStream.getReader().read().then(function (result) {50 t.equals(result.done, true)51 t.end()52 })53})54function streamToString (stream) {55 return new Promise(function (resolve, reject) {56 let reader = stream.getReader()57 let buffer = ''58 reader.read().then(onRead)59 function onRead (result) {60 if (result.done) return resolve(buffer)61 buffer += result.value.toString()62 reader.read().then(onRead)63 }64 })...

Full Screen

Full Screen

base-server.js

Source:base-server.js Github

copy

Full Screen

1/**2 * @method FS.Utility.binaryToBuffer3 * @public4 * @param {Uint8Array} data5 * @returns {Buffer}6 *7 * Converts a Uint8Array instance to a Node Buffer instance8 */9FS.Utility.binaryToBuffer = function(data) {10 var len = data.length;11 var buffer = new Buffer(len);12 for (var i = 0; i < len; i++) {13 buffer[i] = data[i];14 }15 return buffer;16};17/**18 * @method FS.Utility.bufferToBinary19 * @public20 * @param {Buffer} data21 * @returns {Uint8Array}22 *23 * Converts a Node Buffer instance to a Uint8Array instance24 */25FS.Utility.bufferToBinary = function(data) {26 var len = data.length;27 var binary = EJSON.newBinary(len);28 for (var i = 0; i < len; i++) {29 binary[i] = data[i];30 }31 return binary;32};33FS.Utility.safeCallback = function (callback) {34 // Make callback safe for Meteor code35 return Meteor.bindEnvironment(callback, function(err) { throw err; });36};37FS.Utility.safeStream = function(nodestream, name) {38 if (!nodestream || typeof nodestream.on !== 'function')39 throw new Error('Storage Adapter "' + name + '" did not return write stream');40 // Create Meteor safe events41 nodestream.safeOn = function(name, callback) {42 return nodestream.on(name, FS.Utility.safeCallback(callback));43 };44 // Create Meteor safe events45 nodestream.safeOnce = function(name, callback) {46 return nodestream.once(name, FS.Utility.safeCallback(callback));47 };48 // Return the modified stream - modified anyway49 return nodestream;...

Full Screen

Full Screen

read_node_stream.js

Source:read_node_stream.js Github

copy

Full Screen

1export const readNodeStream = (nodeStream) => {2 return new Promise((resolve, reject) => {3 if (nodeStream.isPaused()) {4 nodeStream.resume()5 } else if (nodeStream.complete) {6 resolve(Buffer.from(""))7 return8 }9 const buffers = []10 const errorCallback = (e) => {11 cleanup()12 reject(e)13 }14 const dataCallback = (chunk) => {15 buffers.push(chunk)16 }17 const endCallback = () => {18 const body = Buffer.concat(buffers)19 cleanup()20 resolve(body)21 }22 const cleanup = () => {23 buffers.length = 024 nodeStream.removeListener("data", dataCallback)25 nodeStream.removeListener("error", errorCallback)26 nodeStream.removeListener("end", endCallback)27 nodeStream.destroy()28 }29 nodeStream.on("error", errorCallback)30 nodeStream.on("data", dataCallback)31 nodeStream.on("end", endCallback)32 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const stream = await page.video().nodeStream();7 stream.pipe(fs.createWriteStream('video.mp4'));8 await page.click('text=Sign in');9 await page.fill('input[name="identifier"]', '

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const {chromium, devices} = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext({6 recordVideo: {7 },8 });9 const page = await context.newPage();10 const fileStream = fs.createWriteStream('test.mp4');11 await page.route('**/*', (route) => {12 const interceptedStream = route.request().createReadStream();13 interceptedStream.pipe(fileStream);14 route.continue();15 });16 await page.waitForTimeout(5000);17 await page.close();18 await context.close();19 await browser.close();20})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 const stream = await page.video().nodeStream();6 stream.pipe(process.stdout);7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium, webkit, firefox } = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const video = await page.$('video');8 const stream = await video.nodeStream();9 stream.pipe(fs.createWriteStream('video.mp4'));10 await browser.close();11})();12const { chromium, webkit, firefox } = require('playwright');13const fs = require('fs');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 const video = await page.$('video');19 const stream = await video.nodeStream();20 stream.pipe(fs.createWriteStream('video.mp4'));21 await browser.close();22})();23const { chromium, webkit, firefox } = require('playwright');24const fs = require('fs');25(async () => {26 const browser = await chromium.launch();27 const context = await browser.newContext();28 const page = await context.newPage();29 const video = await page.$('video');30 const stream = await video.nodeStream();31 stream.pipe(fs.createWriteStream('video.mp4'));32 await browser.close();33})();34const { chromium, webkit, firefox } = require('playwright');35const fs = require('fs');36(async () => {37 const browser = await chromium.launch();38 const context = await browser.newContext();39 const page = await context.newPage();40 const video = await page.$('video');41 const stream = await video.nodeStream();42 stream.pipe(fs.createWriteStream('video.mp

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const [request] = await Promise.all([6 page.waitForRequest(request => request.url().includes('test.js')),7 ]);8 const nodeStream = await request.nodeStream();9 nodeStream.on('data', (data) => {10 console.log(data.toString());11 });12 await browser.close();13})();14### 11. Page.waitForFileChooser()15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const page = await browser.newPage();19 const [fileChooser] = await Promise.all([20 page.waitForFileChooser(),21 ]);22 await fileChooser.setFiles('./file-to-upload.pdf');23 await browser.close();24})();25### 12. Page.waitForNavigation()26const { chromium } = require('playwright');27(async () => {28 const browser = await chromium.launch();29 const page = await browser.newPage();30 const response = await page.waitForNavigation();31 console.log(response.url());32 await browser.close();33})();34### 13. Page.waitForRequest()

Full Screen

Using AI Code Generation

copy

Full Screen

1const { nodeStream } = require("playwright/lib/server/stdio");2nodeStream.write("some text");3nodeStream.end();4const { nodeStream } = require("playwright/lib/server/stdio");5nodeStream.write("some text");6nodeStream.end();7const { nodeStream } = require("playwright/lib/server/stdio");8nodeStream.write("some text");9nodeStream.end();10const { nodeStream } = require("playwright/lib/server/stdio");11nodeStream.write("some text");12nodeStream.end();13const { nodeStream } = require("playwright/lib/server/stdio");14nodeStream.write("some text");15nodeStream.end();16const { nodeStream } = require("playwright/lib/server/stdio");17nodeStream.write("some text");18nodeStream.end();19const { nodeStream } = require("playwright/lib/server/stdio");20nodeStream.write("some text");21nodeStream.end();22const { nodeStream } = require("playwright/lib/server/stdio");23nodeStream.write("some text");24nodeStream.end();25const { nodeStream } = require("playwright/lib/server/stdio");26nodeStream.write("some text");27nodeStream.end();28const {

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful