Best JavaScript code snippet using root
AsyncWebSocket.js
Source:AsyncWebSocket.js
...39 this._ws.onerror = this._onError.bind(this);40 this._ws.onmessage = this._onMessage.bind(this);41 this._ws.onclose = this._onClose.bind(this);42 } catch (e) {43 this._unlinkSocket();44 throw new DetoxRuntimeError({45 message: 'Unexpected error occurred when opening a web socket connection.\nSee the error details below.',46 hint: DetoxRuntimeError.reportIssue,47 debugInfo: e,48 });49 }50 return this._opening.promise;51 }52 async close() {53 if (!this._ws) {54 return;55 }56 if (this._closing) {57 throw new DetoxInternalError('Detected an attempt to close an already closing or closed web socket.');58 }59 const closing = this._closing = new Deferred();60 try {61 this._ws.close();62 } catch (error) {63 this._onError({ error });64 }65 return closing.promise;66 }67 async send(message, options = DEFAULT_SEND_OPTIONS) {68 if (!this.isOpen) {69 throw new DetoxRuntimeError({70 message: 'Cannot send a message over the closed web socket. See the payload below:',71 hint: DetoxRuntimeError.reportIssue,72 debugInfo: message,73 });74 }75 if (!_.isNumber(message.messageId)) {76 message.messageId = this._messageIdCounter++;77 }78 const messageId = message.messageId;79 const inFlight = this.inFlightPromises[messageId] = new InflightRequest(message).withTimeout(options.timeout);80 this.handleMultipleNonAtomicPendingActions();81 const messageAsString = JSON.stringify(message);82 this._log.trace(EVENTS.SEND, messageAsString);83 this._ws.send(messageAsString);84 return inFlight.promise;85 }86 handleMultipleNonAtomicPendingActions() {87 const pendingNonAtomicRequests = this.getNonAtomicPendingActions();88 for (const inflight of pendingNonAtomicRequests) {89 inflight.reject(new DetoxRuntimeError({90 message: 'Detox has detected multiple interactions taking place simultaneously. Have you forgotten to apply an await over one of the Detox actions in your test code?',91 }));92 }93 }94 getNonAtomicPendingActions() {95 const remaining = Object.keys(this.inFlightPromises).map((key) => {96 return this.inFlightPromises[key];97 }).filter(item => {98 return item.message.isAtomic === true;99 });100 return remaining.length > 1 ? remaining : [];101 }102 setEventCallback(event, callback) {103 if (_.isEmpty(this._eventCallbacks[event])) {104 this._eventCallbacks[event] = [callback];105 } else {106 this._eventCallbacks[event].push(callback);107 }108 }109 resetInFlightPromises() {110 for (const messageId of _.keys(this.inFlightPromises)) {111 const inFlight = this.inFlightPromises[messageId];112 inFlight.clearTimeout();113 delete this.inFlightPromises[messageId];114 this._abortedMessageIds.add(+messageId);115 }116 }117 // TODO: handle this leaked abstraction some day118 hasPendingActions() {119 return _.some(this.inFlightPromises, p => p.message.type !== 'currentStatus');120 }121 rejectAll(error) {122 const hasPendingActions = this.hasPendingActions();123 const inFlightPromises = _.values(this.inFlightPromises);124 this.resetInFlightPromises();125 for (const inflight of inFlightPromises) {126 inflight.reject(error);127 }128 if (!hasPendingActions) {129 log.error(EVENTS.ERROR, DetoxRuntimeError.format(error));130 }131 }132 get isOpen() {133 return this.status === 'open';134 }135 get status() {136 if (!this._ws) {137 return 'non-initialized';138 }139 switch (this._ws.readyState) {140 case WebSocket.CLOSED: return 'closed';141 case WebSocket.CLOSING: return 'closing';142 case WebSocket.CONNECTING: return 'opening';143 case WebSocket.OPEN: return 'open';144 /* istanbul ignore next */145 default: // TODO: [2021-12-01] throw new DetoxInternalError('...'); instead146 return undefined;147 }148 }149 /**150 * @param {WebSocket.OpenEvent} event151 * @private152 */153 _onOpen(event) { // eslint-disable-line no-unused-vars154 this._log.trace(EVENTS.OPEN, `opened web socket to: ${this._url}`);155 this._opening.resolve();156 this._opening = null;157 }158 /**159 * @param {Error} event.error160 * @private161 */162 _onError(event) {163 const { error } = event;164 if (this._opening && this._opening.isPending()) {165 this._opening.reject(new DetoxRuntimeError({166 message: 'Failed to open a connection to the Detox server.',167 debugInfo: error,168 noStack: true,169 }));170 return this._unlinkSocket();171 }172 if (this._closing && this._closing.isPending()) {173 this._closing.reject(new DetoxRuntimeError({174 message: 'Failed to close a connection to the Detox server.',175 debugInfo: error,176 noStack: true,177 }));178 return this._unlinkSocket();179 }180 this.rejectAll(new DetoxRuntimeError({181 message: 'Failed to deliver the message to the Detox server:',182 debugInfo: error,183 noStack: true,184 }));185 }186 /**187 *188 * @param {WebSocket.MessageEvent} event189 * @private190 */191 _onMessage(event) {192 const data = event && event.data || null;193 try {194 this._log.trace(EVENTS.MESSAGE, data);195 const json = JSON.parse(data);196 if (!json || !json.type) {197 throw new DetoxRuntimeError('Empty or non-typed message received over the web socket.');198 }199 let handled = false;200 if (this.inFlightPromises.hasOwnProperty(json.messageId)) {201 this.inFlightPromises[json.messageId].resolve(json);202 delete this.inFlightPromises[json.messageId];203 handled = true;204 }205 if (this._eventCallbacks.hasOwnProperty(json.type)) {206 for (const callback of this._eventCallbacks[json.type]) {207 callback(json);208 }209 handled = true;210 }211 if (!handled) {212 if (this._abortedMessageIds.has(json.messageId)) {213 log.debug(EVENTS.LATE_RESPONSE, `Received late response for messageId=${json.messageId}`);214 } else {215 throw new DetoxRuntimeError('Unexpected message received over the web socket: ' + json.type);216 }217 }218 } catch (error) {219 this.rejectAll(new DetoxRuntimeError({220 message: 'Unexpected error on an attempt to handle the response received over the web socket.',221 hint: 'Examine the inner error:\n\n' + DetoxRuntimeError.format(error) + '\n\nThe payload was:',222 debugInfo: data,223 }));224 }225 }226 /**227 * @param {WebSocket.CloseEvent | null} event228 * @private229 */230 _onClose(event) { // eslint-disable-line no-unused-vars231 if (this._closing) {232 this._closing.resolve();233 }234 this._unlinkSocket();235 }236 _unlinkSocket() {237 if (this._ws) {238 this._ws.onopen = null;239 this._ws.onerror = null;240 this._ws.onmessage = null;241 this._ws.onclose = null;242 this._ws = null;243 }244 this._opening = null;245 this._closing = null;246 }247}...
SingleInstanceManager.js
Source:SingleInstanceManager.js
...79 }80 else {81 // It somtimes happens on Linux and OS X that the pipe is left behind82 // so we unlink and try again if we think that has happened.83 this._unlinkSocket();84 this._retryCount--;85 return [2 /*return*/, this.ensureSingleInstance(onStartupArgsReceived)];86 }87 return [3 /*break*/, 10];88 case 10: return [2 /*return*/];89 }90 });91 });92 };93 SingleInstanceManager.prototype._tryToCreateMainInstanceServer = function () {94 return NodeIPCFactory_1.default.serve(this._pipeName)95 .then(function (server) {96 return Promise.resolve(server);97 })...
Using AI Code Generation
1var fs = require('fs');2var net = require('net');3var server = net.createServer(function (socket) {4 socket.end('goodbye5');6}).on('error', function (err) {7 throw err;8});9server.listen(function () {10 var address = server.address();11 var client = net.connect(address.port, function () {12 console.log('client connected');13 client.end();14 });15});16server.on('close', function () {17 console.log('server closed');18});19server.unref();20server.close();21var fs = require('fs');22var net = require('net');23var server = net.createServer(function (socket) {24 socket.end('goodbye25');26}).on('error', function (err) {27 throw err;28});29server.listen(function () {30 var address = server.address();31 var client = net.connect(address.port, function () {32 console.log('client connected');33 client.end();34 });35});36server.on('close', function () {37 console.log('server closed');38});39server.unref();40server.close();41And this is the output when I uncomment the server.unref() line:42The server.close() is called in both cases. Why is the server closed in the first case and not in the second case?43And this is the output when I uncomment the server.unref() line:44The server.close() is called in both cases. Why is the server closed in the first case and not in the second case?45server.on('close', function () {46 console.log('server closed');47});
Using AI Code Generation
1var root = require('root');2var socketPath = '/tmp/sock';3root._unlinkSocket(socketPath);4var root = require('root');5var socketPath = '/tmp/sock';6root._unlinkSocket(socketPath);
Using AI Code Generation
1var fs = require('fs');2var net = require('net');3var socket = net.createConnection(1234, 'localhost');4socket.on('connect', function() {5 console.log('client connected');6 fs._unlinkSocket(socket);7 socket.destroy();8});9socket.on('close', function() {10 console.log('client closed');11});12I'm trying to create a server using net.createServer() and I want to use the same port on the same machine again. I'm getting an error saying that the address is already in use. I'm using the following code:13var net = require('net');14var server = net.createServer(function(socket) {15 socket.end('goodbye16');17});18server.listen(1337, '
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!!