How to use readPromise method in wpt

Best JavaScript code snippet using wpt

WebSocketConnection.js

Source:WebSocketConnection.js Github

copy

Full Screen

1const WebSocket = require('ws');2const Agent = require('https').Agent;3class WebSocketConnection {4 constructor(httpUri, fingerprint, signingKey, userAgent) {5 this.signingKey = signingKey;6 this.fingerprint = fingerprint;7 this.userAgent = userAgent;8 this.attempts = 0;9 this.connected = false;10 this.wsUri = httpUri11 .replace("https://", "wss://")12 .replace("http://", "ws://") +13 "/v1/ws";14 this.outgoingRequests = {};15 this.incomingRequests = [];16 this.reconnectCallbacks = [];17 this.callbacks = [];18 this.jsonrpcId = 1;19 this.wasConnected = false;20 }21 connect() {22 let timestamp = parseInt(Date.now() / 1000);23 let data = "GET" + "\n" +24 "/v1/ws" + "\n" +25 timestamp + "\n";26 let signature = this.signingKey.sign(data);27 let options = {28 headers: {29 'Toshi-ID-Address': this.signingKey.address,30 'Toshi-Timestamp': timestamp,31 'Toshi-Signature': signature,32 'User-Agent': this.userAgent33 }34 };35 if (this.fingerprint) {36 Object.assign({37 agent: new Agent({38 maxCachedSessions: 039 }),40 rejectUnauthorized: true41 }, options);42 }43 this.ws = new WebSocket(this.wsUri,44 options);45 if (this.fingerprint) {46 let self = this;47 self.has_connected_once = false;48 let req = this.ws._req;49 req.on('socket', (socket) => {50 socket.on('secureConnect', (x) => {51 let fingerprint = socket.getPeerCertificate().fingerprint;52 if (!fingerprint) {53 req.emit('error', new Error('Missing expected certificate fingerprint'));54 // there is a weird issue where the certificate stuff55 // sometimes goes missing. this case is so that if there56 // has been a secure connection previously, it will retry57 // until the certificate stuff comes back, but if it's58 // missing the first time, then fail straight away.59 if (!self.has_connected_once) {60 return req.abort();61 }62 }63 // Check if certificate is valid64 if (socket.authorized === false) {65 req.emit('error', new Error(socket.authorizationError));66 return req.abort();67 }68 // Match the fingerprint with our saved fingerprints69 if (self.fingerprint.indexOf(fingerprint) === -1) {70 // Abort request, optionally emit an error event71 req.emit('error', new Error('Fingerprint does not match: ' + self.fingerprint + " != " + fingerprint));72 }73 self.has_connected_once = true;74 });75 });76 }77 this.ws.on('open', () => this.onOpen());78 this.ws.on('close', (code, reason) => this.onClose(code, reason));79 this.ws.on('error', (error) => this.onError(error));80 this.ws.on('message', (data) => this.onMessage(data));81 }82 disconnect() {83 if (this.ws) {84 let ws = this.ws;85 this.connected = false;86 this.ws = null;87 this.wasConnected = false;88 ws.close(1000, "OK");89 }90 }91 onOpen() {92 this.connected = true;93 this.attempts = 0;94 if (this.wasConnected) {95 this.reconnectCallbacks.forEach((cb) => cb());96 } else {97 this.wasConnected = true;98 }99 }100 onClose(code, reason) {101 this.connected = false;102 for (var k in this.outgoingRequests) {103 var promise = this.outgoingRequests[k];104 if (promise) {105 // TODO: check status and reject if it's bad106 promise.reject(new Error("Closed: " + code + ", " + reason));107 delete this.outgoingRequests[k];108 }109 }110 if (this.ws) {111 // try reconnect if the connection wasn't closed on purpose112 this.ws = null;113 this.attempts += 1;114 setTimeout(() => {115 this.connect();116 }, Math.min(this.attempts * 200, 15000));117 }118 }119 onError(error) {120 if (this.ws) {121 this.onClose(1000, "OK");122 }123 }124 onMessage(data) {125 let message = JSON.parse(data);126 if ('method' in message) {127 if (this.callbacks) {128 this.callbacks.forEach((callback) => {129 callback([message.method, message.params]);130 });131 } else if (this.readPromise) {132 this.readPromise.fulfil([message.method, message.params]);133 } else {134 this.incomingRequests.push([message.method, message.params]);135 }136 } else if ('id' in message) {137 let promise = this.outgoingRequests[message.id];138 if (promise) {139 if (message.error) promise.reject(message.error);140 else promise.fulfil(message.result);141 delete this.outgoingRequests[message.id];142 }143 }144 }145 readRequest(timeout) {146 if (this.callbacks) {147 throw new Error("Don't call this when using listen: it doesn't make sense!");148 }149 if (this.incomingRequests.length > 0) {150 let request = this.incomingRequests.shift();151 return Promise.resolve(request);152 }153 if (this.readPromise) {154 // TODO: maybe there's a usecase for this155 throw new Error("Websocket is already being read...");156 }157 return new Promise((fulfil, reject) => {158 let timer = timeout ? setTimeout(() => {159 this.readPromise = null;160 reject(new Error("Timeout exceeded"));161 }, timeout) : null;162 this.readPromise = {fulfil: (value) => {163 this.readPromise = null;164 clearTimeout(timer);165 fulfil(value);166 }, reject: (err) => {167 this.readPromise = null;168 clearTimeout(timer);169 reject(err);170 }};171 });172 }173 sendRequest(method, params, retry) {174 let request = {175 jsonrpc: "2.0",176 id: this.jsonrpcId++,177 method: method,178 params: params179 };180 return new Promise((fulfil, reject) => {181 this.outgoingRequests[request.id] = {fulfil: fulfil, reject: reject};182 this._sendRequest(request, 0);183 });184 }185 _sendRequest(request, retry) {186 // wait until websocket is connected before sending the request187 if (this.ws == null || !this.connected) {188 setTimeout(() => this._sendRequest(request, retry ? retry + 1 : 1),189 20 * (retry || 0));190 } else {191 this.ws.send(JSON.stringify(request));192 }193 }194 sendResponse(id, result, error) {195 if (this.ws == null || !this.connected) {196 throw new Error("No connection!");197 }198 let response = {199 jsonrpc: "2.0",200 id: id,201 };202 if (result) {203 response.result = result;204 }205 if (error) {206 result.error = error;207 }208 return new Promise((fulfil, reject) => {209 this.ws.send(JSON.stringify(response), (err) => {210 if (err) {211 reject(err);212 } else {213 fulfil();214 }215 });216 });217 }218 listen(callback) {219 this.callbacks.push(callback);220 // empty out any lingering incomming requests221 if (this.incomingRequests.length > 0) {222 let request = this.incomingRequests.shift();223 callback(request);224 }225 }226 onReconnect(callback) {227 this.reconnectCallbacks.push(callback);228 }229}...

Full Screen

Full Screen

official-locations.js

Source:official-locations.js Github

copy

Full Screen

1const csvParse = require('csv-parse');2const fs = require('fs');3const path = require('path');4const util = require('util');5const njUtils = require('./utils')6const CSV_PATH = path.join(__dirname, 'official-locations-list.csv');7const URL_PROTOCOL = /^https?:\/\//;8function cleanRecord (record) {9 for (let key in record) {10 record[key] = record[key].trim();11 }12 record.simpleName = njUtils.matchable(record['Facility Name']);13 record.simpleAddress = njUtils.matchable(record['Facility Address']);14 record.isMegasite = record['Facility Name']15 .toLowerCase()16 .includes('megasite');17 let url = record['Facility Website'];18 if (url.includes('://covidvaccine.nj.gov')) {19 url = 'https://covidvaccine.nj.gov/';20 }21 else if (url && !URL_PROTOCOL.test(url)) {22 url = 'https://' + url;23 }24 record['Facility Website'] = url;25 return record;26}27async function read () {28 const parser = fs29 .createReadStream(CSV_PATH, {encoding: 'utf-8'})30 .pipe(csvParse({columns: true}));31 result = [];32 for await (const record of parser) {33 result.push(cleanRecord(record));34 }35 return result;36}37let readPromise = null;38let data = null;39/**40 * Get a list of location records.41 * @returns {Promise<Array<object>>}42 */43async function getList () {44 if (!data) {45 if (!readPromise) {46 readPromise = read().then(list => data = list);47 }48 await readPromise;49 }50 return data;51}52module.exports = {53 getList,54 read...

Full Screen

Full Screen

serialwritePromise.js

Source:serialwritePromise.js Github

copy

Full Screen

1const fs=require("fs");2function main(){3 let readpromise=writedata("1.txt");4 for(let i=2;i<=8;i++)5 {6 readpromise=readpromise.then(function(){7 console.log(i-1+" file written");8 return writedata(i+".txt");9 });10 }11 readpromise.then(function(){12 console.log("last file written");13 });14}15function writedata(filename)16{17 let nooflines=Math.floor(Math.random()*101);18 let str="";19 let data;20 for(let i=1;i<=nooflines;i++)21 {22 data=Math.floor(Math.random()*101);23 if(i!=nooflines)24 {25 str=str+data+"\n";26 }27 else28 {29 str=str+data;30 }31 }32 return fs.promises.writeFile(filename,str);33}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.readPromise()4 .then(function (data) {5 console.log(data);6 })7 .catch(function (error) {8 console.log(error);9 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const wiki = wptools.page('Barack Obama');3wiki.get((err, resp) => {4 if (err) {5 console.log(err);6 } else {7 console.log(resp);8 }9});10const wptools = require('wptools');11const wiki = wptools.page('Barack Obama');12wiki.readPromise().then((resp) => {13 console.log(resp);14}).catch((err) => {15 console.log(err);16});17const wptools = require('wptools');18const wiki = wptools.page('Barack Obama');19wiki.read((err, resp) => {20 if (err) {21 console.log(err);22 } else {23 console.log(resp);24 }25});26const wptools = require('wptools');27const wiki = wptools.page('Barack Obama');28wiki.get((err, resp) => {29 if (err) {30 console.log(err);31 } else {32 console.log(resp);33 }34});35const wptools = require('wptools');36const wiki = wptools.page('Barack Obama');37wiki.getPromise().then((resp) => {38 console.log(resp);39}).catch((err) => {40 console.log(err);41});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wiki = wptools.page('Barack Obama');3wiki.get(function(err, resp) {4 if (!err) {5 console.log(resp);6 }7});8var wptools = require('wptools');9var wiki = wptools.page('Barack Obama');10wiki.get(function(err, resp) {11 if (!err) {12 console.log(resp);13 }14});15var wptools = require('wptools');16var wiki = wptools.page('Barack Obama');17wiki.get(function(err, resp) {18 if (!err) {19 console.log(resp);20 }21});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4var data = wptools.page('Barack_Obama').then(function(page) {5 return page.readPromise();6}).then(function(page) {7 return page.data;8}).then(function(data) {9 return data;10}).catch(function(err) {11 console.log(err);12});13const wptools = require('wptools');14const fs = require('fs');15const path = require('path');16wptools.page('Barack_Obama').then(function(page) {17 page.read(function(err, page) {18 if (err) {19 console.log(err);20 }21 console.log(page.data);22 });23});24const wptools = require('wptools');25const fs = require('fs');26const path = require('path');27wptools.page('Barack_Obama').then(function(page) {28 page.read(function(err, page) {29 if (err) {30 console.log(err);31 }32 console.log(page.data);33 });34});35const wptools = require('wptools');36const fs = require('fs');37const path = require('path');38wptools.page('Barack_Obama').then(function(page) {39 page.read(function(err, page) {40 if (err) {41 console.log(err);42 }43 console.log(page.data);44 });45});46const wptools = require('wptools');47const fs = require('fs');48const path = require('path');49wptools.page('Barack_Obama').then(function(page) {50 page.read(function(err, page) {51 if (err) {52 console.log(err);53 }54 console.log(page.data);55 });56});57const wptools = require('wptools');58const fs = require('fs');59const path = require('path');60wptools.page('Barack_Obama').then(function(page) {

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptoolkit = require('wptoolkit');2const path = require('path');3const fs = require('fs');4const pathName = path.join(__dirname, 'test.txt');5const readPromise = wptoolkit.readPromise(pathName);6readPromise.then((data) => {7 console.log(data);8}).catch((err) => {9 console.log(err);10})11const wptoolkit = require('wptoolkit');12const path = require('path');13const fs = require('fs');14const pathName = path.join(__dirname, 'test.txt');15const writePromise = wptoolkit.writePromise(pathName, 'test file contents');16writePromise.then((data) => {17 console.log(data);18}).catch((err) => {19 console.log(err);20})21const wptoolkit = require('wptoolkit');22const path = require('path');23const fs = require('fs');24const sourcePath = path.join(__dirname, 'test.txt');25const destinationPath = path.join(__dirname, 'test-copy.txt');26const copyPromise = wptoolkit.copyPromise(sourcePath, destinationPath);27copyPromise.then((data) => {28 console.log(data);29}).catch((err) => {30 console.log(err);31})32const wptoolkit = require('wptoolkit');33const path = require('path');34const fs = require('fs');35const pathName = path.join(__dirname, 'test.txt');36const deletePromise = wptoolkit.deletePromise(pathName);37deletePromise.then((data) => {38 console.log(data);39}).catch((err) => {40 console.log(err);41})42const wptoolkit = require('wptoolkit');43const path = require('path');44const fs = require('fs');45const sourcePath = path.join(__dirname, 'test.txt');46const destinationPath = path.join(__dirname,

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt');2wpt.readPromise("test.txt")3.then((data) => {4 console.log(data);5})6.catch((err) => {7 console.log(err);8});9# wpt.writePromise(path, data)10const wpt = require('wpt');11wpt.writePromise("test.txt", "This is a test file")12.then(() => {13 console.log("File created successfully");14})15.catch((err) => {16 console.log(err);17});18# wpt.appendPromise(path, data)19const wpt = require('wpt');20wpt.appendPromise("test.txt", "This is a test file")21.then(() => {22 console.log("File created successfully");23})24.catch((err) => {25 console.log(err);26});27# wpt.deletePromise(path)28const wpt = require('wpt');29wpt.deletePromise("test.txt")30.then(() => {31 console.log("File deleted successfully");32})33.catch((err) => {34 console.log(err);35});36# wpt.renamePromise(oldPath, newPath)37const wpt = require('wpt');38wpt.renamePromise("test.txt", "test1.txt")39.then(() => {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var fs = require('fs');3var wikiData = wptools.page('Narendra Modi')4 .get()5 .then(function (data) {6 var file = fs.createWriteStream('test.txt');7 file.on('error', function (err) { /* error handling */ });8 data.infoboxes.forEach(function (v) { file.write(v.text() + '\n'); });9 file.end();10 })11 .catch(function (err) {

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools');2const wiki = wptools.page('Barack Obama');3wiki.get(function(err, resp){4 console.log(resp);5});6![Output](

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt 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