Best JavaScript code snippet using wpt
upload.js
Source:upload.js
1const fs = require("fs");2const path = require("path");3const querystring = require("querystring");4const { errorLog, fsExistsSync, bufferSplit, removeDir } = require("../utils");5const filePath = path.join(__dirname, "../../file");6const outPutDir = path.join(__dirname, "../../out-files");7const temporaryDir = path.join(filePath, "./temporaryDir");8const concatFiles = (res, params) => {9 try {10 if (!fs.existsSync(outPutDir)) {11 fs.mkdirSync(outPutDir);12 }13 const fileName = querystring.parse(params).name;14 const outPutReadable = fs.createWriteStream(path.join(outPutDir, fileName));15 const files = fs16 .readdirSync(temporaryDir)17 .sort((a, b) => a.split("-")[1] - b.split("-")[1]);18 console.log("files", files);19 const streamMergeRecursive = (files, outPutReadable) => {20 // éå½å°å°¾é¨æ
åµå¤æ21 if (!files.length) {22 removeDir(temporaryDir);23 return outPutReadable.end(() => {24 return res.end(25 JSON.stringify({26 code: 200,27 msg: "æä½æå",28 })29 );30 });31 }32 const currentFile = path.join(temporaryDir, "./" + files.shift());33 const currentReadStream = fs.createReadStream(currentFile); // è·åå½åçå¯è¯»æµ34 currentReadStream.pipe(outPutReadable, { end: false });35 currentReadStream.on("end", function () {36 streamMergeRecursive(files, outPutReadable);37 });38 currentReadStream.on("error", function (error) {39 // çå¬é误äºä»¶ï¼å
³éå¯åæµï¼é²æ¢å
åæ³æ¼40 errorLog(error);41 outPutReadable.close();42 });43 };44 streamMergeRecursive(files, outPutReadable);45 } catch (error) {46 errorLog(error);47 return res.end(48 JSON.stringify({49 code: 502,50 msg: "æä½å¤±è´¥",51 })52 );53 }54};55const singleUpload = (req, res) => {56 try {57 const boundary = `--${58 req.headers["content-type"].split("; ")[1].split("=")[1]59 }`; // è·ååé符60 let arr = [];61 if (!fs.existsSync(temporaryDir)) {62 fs.mkdirSync(temporaryDir);63 }64 req.on("data", buffer => {65 arr.push(buffer);66 });67 req.on("end", () => {68 const buffer = Buffer.concat(arr);69 // 1. ç¨<åé符>ååæ°æ®70 let result = bufferSplit(buffer, boundary);71 // 2. å é¤æ°ç»å¤´å°¾æ°æ®72 result.pop();73 result.shift();74 // 3. å°æ¯ä¸é¡¹æ°æ®å¤´å°¾çç\r\nå é¤75 result = result.map(item => item.slice(2, item.length - 2));76 // 4. å°æ¯ä¸é¡¹æ°æ®ä¸é´ç\r\n\r\nå é¤ï¼å¾å°æç»ç»æ77 result.forEach(item => {78 let [info, data] = bufferSplit(item, "\r\n\r\n"); // æ°æ®ä¸å«ææ件信æ¯ï¼ä¿æ为Bufferç±»å79 info = info.toString(); // info为å段信æ¯ï¼è¿æ¯å符串类åæ°æ®ï¼ç´æ¥è½¬æ¢æå符串ï¼è¥ä¸ºæ件信æ¯ï¼åæ°æ®ä¸å«æä¸ä¸ªå车符\r\nï¼å¯ä»¥æ®æ¤å¤ææ°æ®ä¸ºæ件è¿æ¯ä¸ºæ®éæ°æ®ã80 if (info.indexOf("\r\n") >= 0) {81 // è¥ä¸ºæ件信æ¯ï¼åå°Buffer转为æ件ä¿å82 // è·åå段å83 let infoResult = info.split("\r\n")[0].split("; ");84 let name = infoResult[1].split("=")[1];85 name = name.substring(1, name.length - 1);86 // è·åæ件å87 let filename = infoResult[2].split("=")[1];88 filename = filename.substring(1, filename.length - 1);89 // å°æ件åå¨å°æå¡å¨90 fs.writeFile(path.join(temporaryDir, filename), data, err => {91 if (err) {92 errorLog(error);93 return res.end(94 JSON.stringify({95 code: 502,96 msg: "æä½å¤±è´¥",97 })98 );99 }100 return res.end(101 JSON.stringify({102 code: 200,103 msg: "æä½æå",104 })105 );106 });107 } else {108 // è¥ä¸ºæ°æ®ï¼åç´æ¥è·åå段å称åå¼109 let name = info.split("; ")[1].split("=")[1];110 name = name.substring(1, name.length - 1);111 const value = data.toString();112 console.log(name, value);113 }114 });115 });116 } catch (error) {117 errorLog(error);118 return res.end(119 JSON.stringify({120 code: 502,121 msg: "æä½å¤±è´¥",122 })123 );124 }125};126const exists = (res, method, params) => {127 try {128 const fileName = querystring.parse(params)?.name?.slice(0, -4);129 if (fsExistsSync(fileName)) {130 const file = fs.readdirSync(Path.join(filePath, fileName));131 if (file.length !== 0) {132 return res.end(133 JSON.stringify({134 code: 200,135 data: {136 chunkIds: "",137 isExists: false,138 },139 msg: "æä½æå",140 })141 );142 }143 const sortFileList = file.sort(144 (a, b) => b.split("-")[1] - a.split("-")[1]145 );146 return res.end(147 JSON.stringify({148 code: 200,149 data: {150 chunkIds: sortFileList.at(-1),151 isExists: false,152 },153 msg: "æä½å¤±è´¥",154 })155 );156 } else {157 return res.end(158 JSON.stringify({159 code: 200,160 data: {161 chunkIds: "",162 isExists: false,163 },164 msg: "æä½æå",165 })166 );167 }168 } catch (error) {169 errorLog(error);170 return res.end(171 JSON.stringify({172 code: 502,173 msg: "æä½å¤±è´¥",174 })175 );176 }177};...
encode-bad-chunks.any.js
Source:encode-bad-chunks.any.js
1// META: global=worker2// META: script=resources/readable-stream-from-array.js3// META: script=resources/readable-stream-to-array.js4'use strict';5const error1 = new Error('error1');6error1.name = 'error1';7promise_test(t => {8 const ts = new TextEncoderStream();9 const writer = ts.writable.getWriter();10 const reader = ts.readable.getReader();11 const writePromise = writer.write({12 toString() { throw error1; }13 });14 const readPromise = reader.read();15 return Promise.all([16 promise_rejects(t, error1, readPromise, 'read should reject with error1'),17 promise_rejects(t, error1, writePromise, 'write should reject with error1'),18 promise_rejects(t, error1, reader.closed, 'readable should be errored with error1'),19 promise_rejects(t, error1, writer.closed, 'writable should be errored with error1'),20 ]);21}, 'a chunk that cannot be converted to a string should error the streams');22const oddInputs = [23 {24 name: 'undefined',25 value: undefined,26 expected: 'undefined'27 },28 {29 name: 'null',30 value: null,31 expected: 'null'32 },33 {34 name: 'numeric',35 value: 3.14,36 expected: '3.14'37 },38 {39 name: 'object',40 value: {},41 expected: '[object Object]'42 },43 {44 name: 'array',45 value: ['hi'],46 expected: 'hi'47 }48];49for (const input of oddInputs) {50 promise_test(async () => {51 const outputReadable = readableStreamFromArray([input.value])52 .pipeThrough(new TextEncoderStream())53 .pipeThrough(new TextDecoderStream());54 const output = await readableStreamToArray(outputReadable);55 assert_equals(output.length, 1, 'output should contain one chunk');56 assert_equals(output[0], input.expected, 'output should be correct');57 }, `input of type ${input.name} should be converted correctly to string`);...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.log(err);4 wpt.getTestResults(data.data.testId, function(err, data) {5 if (err) return console.log(err);6 console.log(data);7 });8});
Using AI Code Generation
1var wpt = require('./wpt');2 if(err) {3 console.log(err);4 } else {5 wpt.outputReadable(data.data);6 }7});
Using AI Code Generation
1var wpt = require('webpagetest');2var wptServer = wpt('www.webpagetest.org');3var options = {4};5wptServer.runTest(options, function(err, data) {6 if (err) return console.log(err);7 wptServer.outputReadable(data.data.testId, function(err, data) {8 console.log(data);9 });10});
Using AI Code Generation
1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3 console.log(data);4});5var wpt = require('webpagetest');6var client = wpt('www.webpagetest.org');7}, function(err, data) {8 console.log(data);9});10var wpt = require('webpagetest');11var client = wpt('www.webpagetest.org');12}, function(err, data) {13 console.log(data);14});15var wpt = require('webpagetest');16var client = wpt('www.webpagetest.org');17}, function(err, data) {18 console.log(data);19});20var wpt = require('webpagetest');21var client = wpt('www.webpagetest.org');22}, function(err, data) {23 console.log(data);24});25var wpt = require('webpagetest');26var client = wpt('www.webpagetest.org');
Using AI Code Generation
1var wpt = require('wpt-stream');2var fs = require('fs');3var test = new wpt();4var output = fs.createWriteStream('output.json');5test.outputReadable().pipe(output);6### wpt()7### wpt#request(options)8### wpt#outputReadable()9### wpt#outputWritable()10### wpt#outputTransform()11### wpt#outputDuplex()
Using AI Code Generation
1const wpt = require('webpagetest');2const wptClient = wpt('www.webpagetest.org');3const options = {4};5wptClient.runTest(options, (err, data) => {6 if (err) {7 console.error(err);8 } else {9 console.log('Test ID: ' + data.data.testId);10 wptClient.outputReadable(data.data.testId, (err, readableStream) => {11 if (err) {12 console.error(err);13 } else {14 readableStream.on('data', chunk => {15 console.log(chunk.toString());16 });17 }18 });19 }20});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!