benchmark,doc,lib: capitalize more comments

PR-URL: https://github.com/nodejs/node/pull/26849
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
This commit is contained in:
Ruben Bridgewater 2019-03-22 03:44:26 +01:00
parent fd992e6e36
commit b08a867d60
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
232 changed files with 466 additions and 473 deletions

View File

@ -16,7 +16,7 @@ function CLI(usage, settings) {
if (!(this instanceof CLI)) return new CLI(usage, settings); if (!(this instanceof CLI)) return new CLI(usage, settings);
if (process.argv.length < 3) { if (process.argv.length < 3) {
this.abort(usage); // abort will exit the process this.abort(usage); // Abort will exit the process
} }
this.usage = usage; this.usage = usage;

View File

@ -202,7 +202,7 @@ Benchmark.prototype.end = function(operations) {
if (elapsed[0] === 0 && elapsed[1] === 0) { if (elapsed[0] === 0 && elapsed[1] === 0) {
if (!process.env.NODEJS_BENCHMARK_ZERO_ALLOWED) if (!process.env.NODEJS_BENCHMARK_ZERO_ALLOWED)
throw new Error('insufficient clock precision for short benchmark'); throw new Error('insufficient clock precision for short benchmark');
// avoid dividing by zero // Avoid dividing by zero
elapsed[1] = 1; elapsed[1] = 1;
} }

View File

@ -1,4 +1,4 @@
// throughput benchmark // Throughput benchmark
// creates a single hasher, then pushes a bunch of data through it // creates a single hasher, then pushes a bunch of data through it
'use strict'; 'use strict';
const common = require('../common.js'); const common = require('../common.js');

View File

@ -1,4 +1,4 @@
// throughput benchmark // Throughput benchmark
// creates a single hasher, then pushes a bunch of data through it // creates a single hasher, then pushes a bunch of data through it
'use strict'; 'use strict';
const common = require('../common.js'); const common = require('../common.js');

View File

@ -9,7 +9,7 @@ const storedUnicode = Object.create(null);
const useDomains = process.env.NODE_USE_DOMAINS; const useDomains = process.env.NODE_USE_DOMAINS;
// set up one global domain. // Set up one global domain.
if (useDomains) { if (useDomains) {
var domain = require('domain'); var domain = require('domain');
const gdom = domain.create(); const gdom = domain.create();

View File

@ -5,7 +5,7 @@ const PORT = common.PORT;
const cluster = require('cluster'); const cluster = require('cluster');
if (cluster.isMaster) { if (cluster.isMaster) {
var bench = common.createBenchmark(main, { var bench = common.createBenchmark(main, {
// unicode confuses ab on os x. // Unicode confuses ab on os x.
type: ['bytes', 'buffer'], type: ['bytes', 'buffer'],
len: [4, 1024, 102400], len: [4, 1024, 102400],
c: [50, 500] c: [50, 500]

View File

@ -3,7 +3,7 @@ const common = require('../common.js');
const http = require('http'); const http = require('http');
const bench = common.createBenchmark(main, { const bench = common.createBenchmark(main, {
// unicode confuses ab on os x. // Unicode confuses ab on os x.
c: [50, 500], c: [50, 500],
n: [0, 5, 20] n: [0, 5, 20]
}); });

View File

@ -2,7 +2,7 @@
const common = require('../common.js'); const common = require('../common.js');
const bench = common.createBenchmark(main, { const bench = common.createBenchmark(main, {
// unicode confuses ab on os x. // Unicode confuses ab on os x.
type: ['bytes', 'buffer'], type: ['bytes', 'buffer'],
len: [4, 1024, 102400], len: [4, 1024, 102400],
chunks: [1, 4], chunks: [1, 4],

View File

@ -33,7 +33,7 @@ function main({ dur, len, type }) {
const writer = new Writer(); const writer = new Writer();
// the actual benchmark. // The actual benchmark.
const server = net.createServer((socket) => { const server = net.createServer((socket) => {
socket.pipe(writer); socket.pipe(writer);
}); });

View File

@ -34,7 +34,7 @@ function main({ dur, len, type }) {
const reader = new Reader(); const reader = new Reader();
const writer = new Writer(); const writer = new Writer();
// the actual benchmark. // The actual benchmark.
const server = net.createServer((socket) => { const server = net.createServer((socket) => {
socket.pipe(writer); socket.pipe(writer);
}); });

View File

@ -34,7 +34,7 @@ function main({ dur, len, type }) {
const reader = new Reader(); const reader = new Reader();
const writer = new Writer(); const writer = new Writer();
// the actual benchmark. // The actual benchmark.
const server = net.createServer((socket) => { const server = net.createServer((socket) => {
socket.pipe(socket); socket.pipe(socket);
}); });

View File

@ -33,7 +33,7 @@ function main({ dur, len, type }) {
const reader = new Reader(); const reader = new Reader();
const writer = new Writer(); const writer = new Writer();
// the actual benchmark. // The actual benchmark.
const server = net.createServer((socket) => { const server = net.createServer((socket) => {
reader.pipe(socket); reader.pipe(socket);
}); });

View File

@ -38,7 +38,7 @@ function main({ dur, len, type }) {
const reader = new Reader(); const reader = new Reader();
const writer = new Writer(); const writer = new Writer();
// the actual benchmark. // The actual benchmark.
const fakeSocket = new JSStreamWrap(new PassThrough()); const fakeSocket = new JSStreamWrap(new PassThrough());
bench.start(); bench.start();
reader.pipe(fakeSocket); reader.pipe(fakeSocket);

View File

@ -13,7 +13,7 @@ const bench = common.createBenchmark(main, {
function useLegacy(data) { function useLegacy(data) {
const len = data.length; const len = data.length;
var result = url.parse(data[0]); // avoid dead code elimination var result = url.parse(data[0]); // Avoid dead code elimination
bench.start(); bench.start();
for (var i = 0; i < len; ++i) { for (var i = 0; i < len; ++i) {
result = url.parse(data[i]); result = url.parse(data[i]);
@ -24,7 +24,7 @@ function useLegacy(data) {
function useWHATWGWithBase(data) { function useWHATWGWithBase(data) {
const len = data.length; const len = data.length;
var result = new URL(data[0][0], data[0][1]); // avoid dead code elimination var result = new URL(data[0][0], data[0][1]); // Avoid dead code elimination
bench.start(); bench.start();
for (var i = 0; i < len; ++i) { for (var i = 0; i < len; ++i) {
const item = data[i]; const item = data[i];
@ -36,7 +36,7 @@ function useWHATWGWithBase(data) {
function useWHATWGWithoutBase(data) { function useWHATWGWithoutBase(data) {
const len = data.length; const len = data.length;
var result = new URL(data[0]); // avoid dead code elimination var result = new URL(data[0]); // Avoid dead code elimination
bench.start(); bench.start();
for (var i = 0; i < len; ++i) { for (var i = 0; i < len; ++i) {
result = new URL(data[i]); result = new URL(data[i]);

View File

@ -3,7 +3,7 @@ const common = require('../common.js');
const URLSearchParams = require('url').URLSearchParams; const URLSearchParams = require('url').URLSearchParams;
const inputs = { const inputs = {
wpt: 'wpt', // to work around tests wpt: 'wpt', // To work around tests
empty: '', empty: '',
sorted: 'a&b&c&d&e&f&g&h&i&j&k&l&m&n&o&p&q&r&s&t&u&v&w&x&y&z', sorted: 'a&b&c&d&e&f&g&h&i&j&k&l&m&n&o&p&q&r&s&t&u&v&w&x&y&z',
almostsorted: 'a&b&c&d&e&f&g&i&h&j&k&l&m&n&o&p&q&r&s&t&u&w&v&x&y&z', almostsorted: 'a&b&c&d&e&f&g&i&h&j&k&l&m&n&o&p&q&r&s&t&u&w&v&x&y&z',

View File

@ -315,7 +315,7 @@ if (cluster.isMaster) {
} else if (cluster.isWorker) { } else if (cluster.isWorker) {
const net = require('net'); const net = require('net');
const server = net.createServer((socket) => { const server = net.createServer((socket) => {
// connections never end // Connections never end
}); });
server.listen(8000); server.listen(8000);

View File

@ -114,12 +114,12 @@ error output. If `stderr` is not provided, `stdout` is used for `stderr`.
```js ```js
const output = fs.createWriteStream('./stdout.log'); const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log'); const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger // Custom simple logger
const logger = new Console({ stdout: output, stderr: errorOutput }); const logger = new Console({ stdout: output, stderr: errorOutput });
// use it like console // use it like console
const count = 5; const count = 5;
logger.log('count: %d', count); logger.log('count: %d', count);
// in stdout.log: count 5 // In stdout.log: count 5
``` ```
The global `console` is a special `Console` whose output is sent to The global `console` is a special `Console` whose output is sent to

View File

@ -135,7 +135,7 @@ if (cluster.isMaster) {
// But don't keep the process open just for that! // But don't keep the process open just for that!
killtimer.unref(); killtimer.unref();
// stop taking new requests. // Stop taking new requests.
server.close(); server.close();
// Let the master know we're dead. This will trigger a // Let the master know we're dead. This will trigger a
@ -316,14 +316,13 @@ const d = domain.create();
function readSomeFile(filename, cb) { function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind((er, data) => { fs.readFile(filename, 'utf8', d.bind((er, data) => {
// If this throws, it will also be passed to the domain // If this throws, it will also be passed to the domain.
return cb(er, data ? JSON.parse(data) : null); return cb(er, data ? JSON.parse(data) : null);
})); }));
} }
d.on('error', (er) => { d.on('error', (er) => {
// an error occurred somewhere. // An error occurred somewhere. If we throw it now, it will crash the program
// if we throw it now, it will crash the program
// with the normal line number and stack message. // with the normal line number and stack message.
}); });
``` ```
@ -377,7 +376,7 @@ function readSomeFile(filename, cb) {
// callback since it is assumed to be the 'Error' argument // callback since it is assumed to be the 'Error' argument
// and thus intercepted by the domain. // and thus intercepted by the domain.
// if this throws, it will also be passed to the domain // If this throws, it will also be passed to the domain
// so the error-handling logic can be moved to the 'error' // so the error-handling logic can be moved to the 'error'
// event on the domain instead of being repeated throughout // event on the domain instead of being repeated throughout
// the program. // the program.
@ -386,8 +385,7 @@ function readSomeFile(filename, cb) {
} }
d.on('error', (er) => { d.on('error', (er) => {
// an error occurred somewhere. // An error occurred somewhere. If we throw it now, it will crash the program
// if we throw it now, it will crash the program
// with the normal line number and stack message. // with the normal line number and stack message.
}); });
``` ```

View File

@ -407,7 +407,7 @@ program.
try { try {
require('vm').runInThisContext('binary ! isNotOk'); require('vm').runInThisContext('binary ! isNotOk');
} catch (err) { } catch (err) {
// err will be a SyntaxError // 'err' will be a SyntaxError.
} }
``` ```
@ -422,7 +422,7 @@ string would be considered a `TypeError`.
```js ```js
require('url').parse(() => { }); require('url').parse(() => { });
// throws TypeError, since it expected a string // Throws TypeError, since it expected a string.
``` ```
Node.js will generate and throw `TypeError` instances *immediately* as a form Node.js will generate and throw `TypeError` instances *immediately* as a form

View File

@ -648,7 +648,7 @@ emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above // Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log'); const newListeners = emitter.rawListeners('log');
// logs "log persistently" twice // Logs "log persistently" twice
newListeners[0](); newListeners[0]();
emitter.emit('log'); emitter.emit('log');
``` ```

View File

@ -358,7 +358,7 @@ const proxy = http.createServer((req, res) => {
res.end('okay'); res.end('okay');
}); });
proxy.on('connect', (req, cltSocket, head) => { proxy.on('connect', (req, cltSocket, head) => {
// connect to an origin server // Connect to an origin server
const srvUrl = url.parse(`http://${req.url}`); const srvUrl = url.parse(`http://${req.url}`);
const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => { const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
@ -370,7 +370,7 @@ proxy.on('connect', (req, cltSocket, head) => {
}); });
}); });
// now that proxy is running // Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => { proxy.listen(1337, '127.0.0.1', () => {
// Make a request to a tunneling proxy // Make a request to a tunneling proxy
@ -504,7 +504,7 @@ srv.on('upgrade', (req, socket, head) => {
socket.pipe(socket); // echo back socket.pipe(socket); // echo back
}); });
// now that server is running // Now that server is running
srv.listen(1337, '127.0.0.1', () => { srv.listen(1337, '127.0.0.1', () => {
// make a request // make a request
@ -626,11 +626,11 @@ request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body)); request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']); request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type'); const contentType = request.getHeader('Content-Type');
// contentType is 'text/html' // 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length'); const contentLength = request.getHeader('Content-Length');
// contentLength is of type number // 'contentLength' is of type number
const cookie = request.getHeader('Cookie'); const cookie = request.getHeader('Cookie');
// cookie is of type string[] // 'cookie' is of type string[]
``` ```
### request.maxHeadersCount ### request.maxHeadersCount
@ -745,7 +745,7 @@ req.once('response', (res) => {
const ip = req.socket.localAddress; const ip = req.socket.localAddress;
const port = req.socket.localPort; const port = req.socket.localPort;
console.log(`Your IP address is ${ip} and your source port is ${port}.`); console.log(`Your IP address is ${ip} and your source port is ${port}.`);
// consume response object // Consume response object
}); });
``` ```
@ -2065,7 +2065,7 @@ req.on('error', (e) => {
console.error(`problem with request: ${e.message}`); console.error(`problem with request: ${e.message}`);
}); });
// write data to request body // Write data to request body
req.write(postData); req.write(postData);
req.end(); req.end();
``` ```

View File

@ -2437,7 +2437,7 @@ const client = http2.connect('http://localhost');
client.on('stream', (pushedStream, requestHeaders) => { client.on('stream', (pushedStream, requestHeaders) => {
pushedStream.on('push', (responseHeaders) => { pushedStream.on('push', (responseHeaders) => {
// process response headers // Process response headers
}); });
pushedStream.on('data', (chunk) => { /* handle pushed data */ }); pushedStream.on('data', (chunk) => { /* handle pushed data */ });
}); });

View File

@ -295,8 +295,8 @@ process.on('unhandledRejection', (reason, p) => {
}); });
somePromise.then((res) => { somePromise.then((res) => {
return reportToUser(JSON.pasre(res)); // note the typo (`pasre`) return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // no `.catch()` or `.then()` }); // No `.catch()` or `.then()`
``` ```
The following will also trigger the `'unhandledRejection'` event to be The following will also trigger the `'unhandledRejection'` event to be

View File

@ -126,7 +126,7 @@ querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge=' // Returns 'foo=bar&baz=qux&baz=quux&corge='
querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// returns 'foo:bar;baz:qux' // Returns 'foo:bar;baz:qux'
``` ```
By default, characters requiring percent-encoding within the query string will By default, characters requiring percent-encoding within the query string will

View File

@ -683,7 +683,7 @@ pass.unpipe(writable);
// readableFlowing is now false // readableFlowing is now false
pass.on('data', (chunk) => { console.log(chunk.toString()); }); pass.on('data', (chunk) => { console.log(chunk.toString()); });
pass.write('ok'); // will not emit 'data' pass.write('ok'); // Will not emit 'data'
pass.resume(); // Must be called to make stream emit 'data' pass.resume(); // Must be called to make stream emit 'data'
``` ```
@ -1206,7 +1206,7 @@ function parseHeader(stream, callback) {
while (null !== (chunk = stream.read())) { while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk); const str = decoder.write(chunk);
if (str.match(/\n\n/)) { if (str.match(/\n\n/)) {
// found the header boundary // Found the header boundary
const split = str.split(/\n\n/); const split = str.split(/\n\n/);
header += split.shift(); header += split.shift();
const remaining = split.join('\n\n'); const remaining = split.join('\n\n');
@ -1219,7 +1219,7 @@ function parseHeader(stream, callback) {
// Now the body of the message can be read from the stream. // Now the body of the message can be read from the stream.
callback(null, header, stream); callback(null, header, stream);
} else { } else {
// still reading the header. // Still reading the header.
header += str; header += str;
} }
} }

View File

@ -163,7 +163,7 @@ setImmediatePromise('foobar').then((value) => {
// This is executed after all I/O callbacks. // This is executed after all I/O callbacks.
}); });
// or with async function // Or with async function
async function timerExample() { async function timerExample() {
console.log('Before I/O callbacks'); console.log('Before I/O callbacks');
await setImmediatePromise(); await setImmediatePromise();

View File

@ -758,7 +758,7 @@ option properties directly is also supported.
const util = require('util'); const util = require('util');
const arr = Array(101).fill(0); const arr = Array(101).fill(0);
console.log(arr); // logs the truncated array console.log(arr); // Logs the truncated array
util.inspect.defaultOptions.maxArrayLength = null; util.inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full array console.log(arr); // logs the full array
``` ```

View File

@ -69,7 +69,7 @@ See [Memory Usage Tuning][] for more information on the speed/memory/compression
tradeoffs involved in `zlib` usage. tradeoffs involved in `zlib` usage.
```js ```js
// client request example // Client request example
const zlib = require('zlib'); const zlib = require('zlib');
const http = require('http'); const http = require('http');
const fs = require('fs'); const fs = require('fs');

View File

@ -239,10 +239,10 @@ function writeHead(statusCode, reason, obj) {
if (k === undefined && this._header) { if (k === undefined && this._header) {
throw new ERR_HTTP_HEADERS_SENT('render'); throw new ERR_HTTP_HEADERS_SENT('render');
} }
// only progressive api is used // Only progressive api is used
headers = this[outHeadersKey]; headers = this[outHeadersKey];
} else { } else {
// only writeHead() called // Only writeHead() called
headers = obj; headers = obj;
} }
@ -440,7 +440,7 @@ function socketOnTimeout() {
function socketOnClose(socket, state) { function socketOnClose(socket, state) {
debug('server socket close'); debug('server socket close');
// mark this parser as reusable // Mark this parser as reusable
if (socket.parser) { if (socket.parser) {
freeParser(socket.parser, null, socket); freeParser(socket.parser, null, socket);
} }
@ -455,7 +455,7 @@ function abortIncoming(incoming) {
req.emit('aborted'); req.emit('aborted');
req.emit('close'); req.emit('close');
} }
// abort socket._httpMessage ? // Abort socket._httpMessage ?
} }
function socketOnEnd(server, socket, parser, state) { function socketOnEnd(server, socket, parser, state) {

View File

@ -96,13 +96,13 @@ Object.defineProperty(Duplex.prototype, 'writableLength', {
} }
}); });
// the no-half-open enforcer // The no-half-open enforcer
function onend() { function onend() {
// If the writable side ended, then we're ok. // If the writable side ended, then we're ok.
if (this._writableState.ended) if (this._writableState.ended)
return; return;
// no more data can be written. // No more data can be written.
// But allow more writes to happen in this tick. // But allow more writes to happen in this tick.
process.nextTick(onEndNT, this); process.nextTick(onEndNT, this);
} }

View File

@ -130,7 +130,7 @@ function ReadableState(options, stream, isDuplex) {
// Should .destroy() be called after 'end' (and potentially 'finish') // Should .destroy() be called after 'end' (and potentially 'finish')
this.autoDestroy = !!options.autoDestroy; this.autoDestroy = !!options.autoDestroy;
// has it been destroyed // Has it been destroyed
this.destroyed = false; this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string // Crypto is kind of old and crusty. Historically, its default string
@ -295,7 +295,7 @@ function addChunk(stream, state, chunk, addToFront) {
state.awaitDrain = 0; state.awaitDrain = 0;
stream.emit('data', chunk); stream.emit('data', chunk);
} else { } else {
// update the buffer info. // Update the buffer info.
state.length += state.objectMode ? 1 : chunk.length; state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) if (addToFront)
state.buffer.unshift(chunk); state.buffer.unshift(chunk);
@ -323,7 +323,7 @@ Readable.prototype.isPaused = function() {
return this._readableState.flowing === false; return this._readableState.flowing === false;
}; };
// backwards compatibility. // Backwards compatibility.
Readable.prototype.setEncoding = function(enc) { Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder) if (!StringDecoder)
StringDecoder = require('string_decoder').StringDecoder; StringDecoder = require('string_decoder').StringDecoder;
@ -459,7 +459,7 @@ Readable.prototype.read = function(n) {
// If the length is currently zero, then we *need* a readable event. // If the length is currently zero, then we *need* a readable event.
if (state.length === 0) if (state.length === 0)
state.needReadable = true; state.needReadable = true;
// call internal read method // Call internal read method
this._read(state.highWaterMark); this._read(state.highWaterMark);
state.sync = false; state.sync = false;
// If _read pushed data synchronously, then `reading` will be false, // If _read pushed data synchronously, then `reading` will be false,
@ -818,7 +818,7 @@ Readable.prototype.unpipe = function(dest) {
return this; return this;
} }
// try to find the right one. // Try to find the right one.
var index = state.pipes.indexOf(dest); var index = state.pipes.indexOf(dest);
if (index === -1) if (index === -1)
return this; return this;
@ -1006,8 +1006,7 @@ Readable.prototype.wrap = function(stream) {
} }
}); });
// proxy all the other methods. // Proxy all the other methods. Important when wrapping filters and duplexes.
// important when wrapping filters and duplexes.
for (var i in stream) { for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') { if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function methodWrap(method) { this[i] = function methodWrap(method) {

View File

@ -80,14 +80,14 @@ function WritableState(options, stream, isDuplex) {
// drain event flag. // drain event flag.
this.needDrain = false; this.needDrain = false;
// at the start of calling end() // At the start of calling end()
this.ending = false; this.ending = false;
// When end() has been called, and returned // When end() has been called, and returned
this.ended = false; this.ended = false;
// when 'finish' is emitted // When 'finish' is emitted
this.finished = false; this.finished = false;
// has it been destroyed // Has it been destroyed
this.destroyed = false; this.destroyed = false;
// Should we decode strings into buffers before passing to _write? // Should we decode strings into buffers before passing to _write?
@ -152,7 +152,7 @@ function WritableState(options, stream, isDuplex) {
// Should .destroy() be called after 'finish' (and potentially 'end') // Should .destroy() be called after 'finish' (and potentially 'end')
this.autoDestroy = !!options.autoDestroy; this.autoDestroy = !!options.autoDestroy;
// count buffered requests // Count buffered requests
this.bufferedRequestCount = 0; this.bufferedRequestCount = 0;
// Allocate the first CorkedRequest, there is always // Allocate the first CorkedRequest, there is always
@ -681,7 +681,7 @@ function onCorkedFinish(corkReq, state, err) {
entry = entry.next; entry = entry.next;
} }
// reuse the free corkReq. // Reuse the free corkReq.
state.corkedRequestsFree.next = corkReq; state.corkedRequestsFree.next = corkReq;
} }

View File

@ -356,7 +356,7 @@ function fromArrayLike(obj) {
} }
function fromArrayBuffer(obj, byteOffset, length) { function fromArrayBuffer(obj, byteOffset, length) {
// convert byteOffset to integer // Convert byteOffset to integer
if (byteOffset === undefined) { if (byteOffset === undefined) {
byteOffset = 0; byteOffset = 0;
} else { } else {

View File

@ -262,7 +262,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) {
address = '::'; address = '::';
} }
// resolve address first // Resolve address first
state.handle.lookup(address, (err, ip) => { state.handle.lookup(address, (err, ip) => {
if (err) { if (err) {
state.bindState = BIND_STATE_UNBOUND; state.bindState = BIND_STATE_UNBOUND;

View File

@ -68,7 +68,7 @@ const asyncHook = createHook({
}, },
before(asyncId) { before(asyncId) {
const current = pairing.get(asyncId); const current = pairing.get(asyncId);
if (current !== undefined) { // enter domain for this cb if (current !== undefined) { // Enter domain for this cb
// We will get the domain through current.get(), because the resource // We will get the domain through current.get(), because the resource
// object's .domain property makes sure it is not garbage collected. // object's .domain property makes sure it is not garbage collected.
current.get().enter(); current.get().enter();
@ -76,7 +76,7 @@ const asyncHook = createHook({
}, },
after(asyncId) { after(asyncId) {
const current = pairing.get(asyncId); const current = pairing.get(asyncId);
if (current !== undefined) { // exit domain for this cb if (current !== undefined) { // Exit domain for this cb
current.get().exit(); current.get().exit();
} }
}, },

View File

@ -121,7 +121,7 @@ function handleErrorFromBinding(ctx) {
Error.captureStackTrace(err, handleErrorFromBinding); Error.captureStackTrace(err, handleErrorFromBinding);
throw err; throw err;
} }
if (ctx.error !== undefined) { // errors created in C++ land. if (ctx.error !== undefined) { // Errors created in C++ land.
// TODO(joyeecheung): currently, ctx.error are encoding errors // TODO(joyeecheung): currently, ctx.error are encoding errors
// usually caused by memory problems. We need to figure out proper error // usually caused by memory problems. We need to figure out proper error
// code(s) for this. // code(s) for this.
@ -289,7 +289,7 @@ function readFile(path, options, callback) {
if (!ReadFileContext) if (!ReadFileContext)
ReadFileContext = require('internal/fs/read_file_context'); ReadFileContext = require('internal/fs/read_file_context');
const context = new ReadFileContext(callback, options.encoding); const context = new ReadFileContext(callback, options.encoding);
context.isUserFd = isFd(path); // file descriptor ownership context.isUserFd = isFd(path); // File descriptor ownership
const req = new FSReqCallback(); const req = new FSReqCallback();
req.context = context; req.context = context;
@ -349,14 +349,14 @@ function tryReadSync(fd, isUserFd, buffer, pos, len) {
function readFileSync(path, options) { function readFileSync(path, options) {
options = getOptions(options, { flag: 'r' }); options = getOptions(options, { flag: 'r' });
const isUserFd = isFd(path); // file descriptor ownership const isUserFd = isFd(path); // File descriptor ownership
const fd = isUserFd ? path : fs.openSync(path, options.flag, 0o666); const fd = isUserFd ? path : fs.openSync(path, options.flag, 0o666);
const stats = tryStatSync(fd, isUserFd); const stats = tryStatSync(fd, isUserFd);
const size = isFileType(stats, S_IFREG) ? stats[8] : 0; const size = isFileType(stats, S_IFREG) ? stats[8] : 0;
let pos = 0; let pos = 0;
let buffer; // single buffer with file data let buffer; // Single buffer with file data
let buffers; // list for when size is unknown let buffers; // List for when size is unknown
if (size === 0) { if (size === 0) {
buffers = []; buffers = [];
@ -1242,7 +1242,7 @@ function writeFileSync(path, data, options) {
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' }); options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
const flag = options.flag || 'w'; const flag = options.flag || 'w';
const isUserFd = isFd(path); // file descriptor ownership const isUserFd = isFd(path); // File descriptor ownership
const fd = isUserFd ? path : fs.openSync(path, flag, options.mode); const fd = isUserFd ? path : fs.openSync(path, flag, options.mode);
if (!isArrayBufferView(data)) { if (!isArrayBufferView(data)) {

View File

@ -565,7 +565,7 @@ function setupChannel(target, channel) {
// Object where socket lists will live // Object where socket lists will live
channel.sockets = { got: {}, send: {} }; channel.sockets = { got: {}, send: {} };
// handlers will go through this // Handlers will go through this
target.on('internalMessage', function(message, handle) { target.on('internalMessage', function(message, handle) {
// Once acknowledged - continue sending handles. // Once acknowledged - continue sending handles.
if (message.cmd === 'NODE_HANDLE_ACK' || if (message.cmd === 'NODE_HANDLE_ACK' ||

View File

@ -14,7 +14,7 @@
// limitations under the License. // limitations under the License.
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// based upon: // Based upon:
// https://github.com/google/caja/blob/master/src/com/google/caja/ses/startSES.js // https://github.com/google/caja/blob/master/src/com/google/caja/ses/startSES.js
// https://github.com/google/caja/blob/master/src/com/google/caja/ses/repairES5.js // https://github.com/google/caja/blob/master/src/com/google/caja/ses/repairES5.js
// https://github.com/tc39/proposal-frozen-realms/blob/91ac390e3451da92b5c27e354b39e52b7636a437/shim/src/deep-freeze.js // https://github.com/tc39/proposal-frozen-realms/blob/91ac390e3451da92b5c27e354b39e52b7636a437/shim/src/deep-freeze.js
@ -176,11 +176,11 @@ module.exports = function() {
// NB: handle for any new cases in future // NB: handle for any new cases in future
} }
if (frozenSet.has(val) || freezingSet.has(val)) { if (frozenSet.has(val) || freezingSet.has(val)) {
// todo use uncurried form // TODO: Use uncurried form
// Ignore if already frozen or freezing // Ignore if already frozen or freezing
return; return;
} }
freezingSet.add(val); // todo use uncurried form freezingSet.add(val); // TODO: Use uncurried form
} }
function doFreeze(obj) { function doFreeze(obj) {
@ -201,8 +201,8 @@ module.exports = function() {
const descs = getOwnPropertyDescriptors(obj); const descs = getOwnPropertyDescriptors(obj);
enqueue(proto); enqueue(proto);
ownKeys(descs).forEach((name) => { ownKeys(descs).forEach((name) => {
// todo uncurried form // TODO: Uncurried form
// todo: getOwnPropertyDescriptors is guaranteed to return well-formed // TODO: getOwnPropertyDescriptors is guaranteed to return well-formed
// descriptors, but they still inherit from Object.prototype. If // descriptors, but they still inherit from Object.prototype. If
// someone has poisoned Object.prototype to add 'value' or 'get' // someone has poisoned Object.prototype to add 'value' or 'get'
// properties, then a simple 'if ("value" in desc)' or 'desc.value' // properties, then a simple 'if ("value" in desc)' or 'desc.value'
@ -222,12 +222,12 @@ module.exports = function() {
function dequeue() { function dequeue() {
// New values added before forEach() has finished will be visited. // New values added before forEach() has finished will be visited.
freezingSet.forEach(doFreeze); // todo curried forEach freezingSet.forEach(doFreeze); // TODO: Curried forEach
} }
function commit() { function commit() {
// todo curried forEach // TODO: Curried forEach
// we capture the real WeakSet.prototype.add above, in case someone // We capture the real WeakSet.prototype.add above, in case someone
// changes it. The two-argument form of forEach passes the second // changes it. The two-argument form of forEach passes the second
// argument as the 'this' binding, so we add to the correct set. // argument as the 'this' binding, so we add to the correct set.
freezingSet.forEach(frozenSet.add, frozenSet); freezingSet.forEach(frozenSet.add, frozenSet);

View File

@ -121,7 +121,7 @@ ReadStream.prototype.open = function() {
this.fd = fd; this.fd = fd;
this.emit('open', fd); this.emit('open', fd);
this.emit('ready'); this.emit('ready');
// start the flow of data. // Start the flow of data.
this.read(); this.read();
}); });
}; };
@ -137,7 +137,7 @@ ReadStream.prototype._read = function(n) {
return; return;
if (!pool || pool.length - pool.used < kMinPoolSpace) { if (!pool || pool.length - pool.used < kMinPoolSpace) {
// discard the old pool. // Discard the old pool.
allocNewPool(this.readableHighWaterMark); allocNewPool(this.readableHighWaterMark);
} }

View File

@ -711,7 +711,7 @@ Module.prototype.load = function(filename) {
const module = ESMLoader.moduleMap.get(url); const module = ESMLoader.moduleMap.get(url);
// Create module entry at load time to snapshot exports correctly // Create module entry at load time to snapshot exports correctly
const exports = this.exports; const exports = this.exports;
if (module !== undefined) { // called from cjs translator if (module !== undefined) { // Called from cjs translator
module.reflect.onReady((reflect) => { module.reflect.onReady((reflect) => {
reflect.exports.default.set(exports); reflect.exports.default.set(exports);
}); });
@ -885,7 +885,7 @@ if (experimentalModules) {
}; };
} }
// bootstrap main module. // Bootstrap main module.
Module.runMain = function() { Module.runMain = function() {
// Load the main module--the command line argument. // Load the main module--the command line argument.
if (experimentalModules) { if (experimentalModules) {

View File

@ -86,7 +86,7 @@ translators.set('cjs', async (url, isMain) => {
// through normal resolution // through normal resolution
translators.set('builtin', async (url) => { translators.set('builtin', async (url) => {
debug(`Translating BuiltinModule ${url}`); debug(`Translating BuiltinModule ${url}`);
// slice 'node:' scheme // Slice 'node:' scheme
const id = url.slice(5); const id = url.slice(5);
const module = NativeModule.map.get(id); const module = NativeModule.map.get(id);
if (!module) { if (!module) {

View File

@ -167,7 +167,7 @@ function wrapProcessMethods(binding) {
throw new ERR_INVALID_ARG_TYPE('pid', 'number', pid); throw new ERR_INVALID_ARG_TYPE('pid', 'number', pid);
} }
// preserve null signal // Preserve null signal
if (sig === (sig | 0)) { if (sig === (sig | 0)) {
// XXX(joyeecheung): we have to use process._kill here because // XXX(joyeecheung): we have to use process._kill here because
// it's monkey-patched by tests. // it's monkey-patched by tests.
@ -268,12 +268,12 @@ function buildAllowedFlags() {
} }
delete() { delete() {
// noop, `Set` API compatible // No-op, `Set` API compatible
return false; return false;
} }
clear() { clear() {
// noop // No-op
} }
has(key) { has(key) {

View File

@ -186,7 +186,7 @@ function* emitKeys(stream) {
} }
if (escaped && (ch === 'O' || ch === '[')) { if (escaped && (ch === 'O' || ch === '[')) {
// ansi escape sequence // ANSI escape sequence
let code = ch; let code = ch;
let modifier = 0; let modifier = 0;
@ -407,7 +407,7 @@ function* emitKeys(stream) {
key.name = String.fromCharCode(ch.charCodeAt(0) + 'a'.charCodeAt(0) - 1); key.name = String.fromCharCode(ch.charCodeAt(0) + 'a'.charCodeAt(0) - 1);
key.ctrl = true; key.ctrl = true;
} else if (/^[0-9A-Za-z]$/.test(ch)) { } else if (/^[0-9A-Za-z]$/.test(ch)) {
// letter, number, shift+letter // Letter, number, shift+letter
key.name = ch.toLowerCase(); key.name = ch.toLowerCase();
key.shift = /^[A-Z]$/.test(ch); key.shift = /^[A-Z]$/.test(ch);
key.meta = escaped; key.meta = escaped;

View File

@ -18,9 +18,7 @@ function readAndResolve(iter) {
const resolve = iter[kLastResolve]; const resolve = iter[kLastResolve];
if (resolve !== null) { if (resolve !== null) {
const data = iter[kStream].read(); const data = iter[kStream].read();
// we defer if data is null // We defer if data is null. We can be expecting either 'end' or 'error'.
// we can be expecting either 'end' or
// 'error'
if (data !== null) { if (data !== null) {
iter[kLastPromise] = null; iter[kLastPromise] = null;
iter[kLastResolve] = null; iter[kLastResolve] = null;
@ -32,7 +30,7 @@ function readAndResolve(iter) {
function onReadable(iter) { function onReadable(iter) {
// We wait for the next tick, because it might // We wait for the next tick, because it might
// emit an error with process.nextTick // emit an error with `process.nextTick()`.
process.nextTick(readAndResolve, iter); process.nextTick(readAndResolve, iter);
} }
@ -59,7 +57,7 @@ const ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf({
next() { next() {
// If we have detected an error in the meanwhile // If we have detected an error in the meanwhile
// reject straight away // reject straight away.
const error = this[kError]; const error = this[kError];
if (error !== null) { if (error !== null) {
return Promise.reject(error); return Promise.reject(error);
@ -110,9 +108,9 @@ const ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf({
}, },
return() { return() {
// destroy(err, cb) is a private API // destroy(err, cb) is a private API.
// we can guarantee we have that here, because we control the // We can guarantee we have that here, because we control the
// Readable class this is attached to // Readable class this is attached to.
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this[kStream].destroy(null, (err) => { this[kStream].destroy(null, (err) => {
if (err) { if (err) {
@ -135,9 +133,8 @@ const createReadableStreamAsyncIterator = (stream) => {
value: stream._readableState.endEmitted, value: stream._readableState.endEmitted,
writable: true writable: true
}, },
// The function passed to new Promise // The function passed to new Promise is cached so we avoid allocating a new
// is cached so we avoid allocating a new // closure at every run.
// closure at every run
[kHandlePromise]: { [kHandlePromise]: {
value: (resolve, reject) => { value: (resolve, reject) => {
const data = iterator[kStream].read(); const data = iterator[kStream].read();
@ -159,8 +156,8 @@ const createReadableStreamAsyncIterator = (stream) => {
finished(stream, (err) => { finished(stream, (err) => {
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
const reject = iterator[kLastReject]; const reject = iterator[kLastReject];
// Reject if we are waiting for data in the Promise // Reject if we are waiting for data in the Promise returned by next() and
// returned by next() and store the error // store the error.
if (reject !== null) { if (reject !== null) {
iterator[kLastPromise] = null; iterator[kLastPromise] = null;
iterator[kLastResolve] = null; iterator[kLastResolve] = null;

View File

@ -154,7 +154,7 @@ function initAsyncResource(resource, type) {
// Timer constructor function. // Timer constructor function.
// The entire prototype is defined in lib/timers.js // The entire prototype is defined in lib/timers.js
function Timeout(callback, after, args, isRepeat) { function Timeout(callback, after, args, isRepeat) {
after *= 1; // coalesce to number or NaN after *= 1; // Coalesce to number or NaN
if (!(after >= 1 && after <= TIMEOUT_MAX)) { if (!(after >= 1 && after <= TIMEOUT_MAX)) {
if (after > TIMEOUT_MAX) { if (after > TIMEOUT_MAX) {
process.emitWarning(`${after} does not fit into` + process.emitWarning(`${after} does not fit into` +

View File

@ -60,7 +60,7 @@ function createHook() {
trace(kEndEvent, kTraceEventCategory, type, asyncId); trace(kEndEvent, kTraceEventCategory, type, asyncId);
// cleanup asyncId to type map // Cleanup asyncId to type map
typeMemory.delete(asyncId); typeMemory.delete(asyncId);
} }
}); });

View File

@ -136,7 +136,7 @@ class URLSearchParams {
throw new ERR_ARG_NOT_ITERABLE('Query pairs'); throw new ERR_ARG_NOT_ITERABLE('Query pairs');
} }
// sequence<sequence<USVString>> // Sequence<sequence<USVString>>
// Note: per spec we have to first exhaust the lists then process them // Note: per spec we have to first exhaust the lists then process them
const pairs = []; const pairs = [];
for (const pair of init) { for (const pair of init) {
@ -159,7 +159,7 @@ class URLSearchParams {
this[searchParams].push(pair[0], pair[1]); this[searchParams].push(pair[0], pair[1]);
} }
} else { } else {
// record<USVString, USVString> // Record<USVString, USVString>
// Need to use reflection APIs for full spec compliance. // Need to use reflection APIs for full spec compliance.
this[searchParams] = []; this[searchParams] = [];
const keys = Reflect.ownKeys(init); const keys = Reflect.ownKeys(init);
@ -230,7 +230,7 @@ function onParseComplete(flags, protocol, username, password,
ctx.query = query; ctx.query = query;
ctx.fragment = fragment; ctx.fragment = fragment;
ctx.host = host; ctx.host = host;
if (!this[searchParams]) { // invoked from URL constructor if (!this[searchParams]) { // Invoked from URL constructor
this[searchParams] = new URLSearchParams(); this[searchParams] = new URLSearchParams();
this[searchParams][context] = this; this[searchParams][context] = this;
} }
@ -455,7 +455,7 @@ Object.defineProperties(URL.prototype, {
try { try {
return (new URL(ctx.path[0])).origin; return (new URL(ctx.path[0])).origin;
} catch { } catch {
// fall through... do nothing // Fall through... do nothing
} }
} }
return kOpaqueOrigin; return kOpaqueOrigin;

View File

@ -1261,7 +1261,7 @@ function emitErrorNT(self, err) {
function emitListeningNT(self) { function emitListeningNT(self) {
// ensure handle hasn't closed // Ensure handle hasn't closed
if (self._handle) if (self._handle)
self.emit('listening'); self.emit('listening');
} }

View File

@ -96,7 +96,7 @@ function Interface(input, output, completer, terminal) {
let prompt = '> '; let prompt = '> ';
if (input && input.input) { if (input && input.input) {
// an options object was given // An options object was given
output = input.output; output = input.output;
completer = input.completer; completer = input.completer;
terminal = input.terminal; terminal = input.terminal;
@ -222,7 +222,7 @@ function Interface(input, output, completer, terminal) {
emitKeypressEvents(input, this); emitKeypressEvents(input, this);
// input usually refers to stdin // `input` usually refers to stdin
input.on('keypress', onkeypress); input.on('keypress', onkeypress);
input.on('end', ontermend); input.on('end', ontermend);
@ -496,7 +496,7 @@ Interface.prototype._tabComplete = function(lastKeypressWasTab) {
} }
const completions = rv[0]; const completions = rv[0];
const completeOn = rv[1]; // the text that was completed const completeOn = rv[1]; // The text that was completed
if (completions && completions.length) { if (completions && completions.length) {
// Apply/show completions. // Apply/show completions.
if (lastKeypressWasTab) { if (lastKeypressWasTab) {
@ -688,7 +688,7 @@ Interface.prototype._historyNext = function() {
if (this.historyIndex > 0) { if (this.historyIndex > 0) {
this.historyIndex--; this.historyIndex--;
this.line = this.history[this.historyIndex]; this.line = this.history[this.historyIndex];
this.cursor = this.line.length; // set cursor to end of line. this.cursor = this.line.length; // Set cursor to end of line.
this._refreshLine(); this._refreshLine();
} else if (this.historyIndex === 0) { } else if (this.historyIndex === 0) {
@ -704,7 +704,7 @@ Interface.prototype._historyPrev = function() {
if (this.historyIndex + 1 < this.history.length) { if (this.historyIndex + 1 < this.history.length) {
this.historyIndex++; this.historyIndex++;
this.line = this.history[this.historyIndex]; this.line = this.history[this.historyIndex];
this.cursor = this.line.length; // set cursor to end of line. this.cursor = this.line.length; // Set cursor to end of line.
this._refreshLine(); this._refreshLine();
} }
@ -814,7 +814,7 @@ function _ttyWriteDumb(s, key) {
} }
switch (key.name) { switch (key.name) {
case 'return': // carriage return, i.e. \r case 'return': // Carriage return, i.e. \r
this._sawReturnAt = Date.now(); this._sawReturnAt = Date.now();
this._line(); this._line();
break; break;
@ -837,7 +837,7 @@ function _ttyWriteDumb(s, key) {
} }
} }
// handle a write from the tty // Handle a write from the tty
Interface.prototype._ttyWrite = function(s, key) { Interface.prototype._ttyWrite = function(s, key) {
const previousKey = this._previousKey; const previousKey = this._previousKey;
key = key || {}; key = key || {};
@ -893,11 +893,11 @@ Interface.prototype._ttyWrite = function(s, key) {
this._deleteLineRight(); this._deleteLineRight();
break; break;
case 'a': // go to the start of the line case 'a': // Go to the start of the line
this._moveCursor(-Infinity); this._moveCursor(-Infinity);
break; break;
case 'e': // go to the end of the line case 'e': // Go to the end of the line
this._moveCursor(+Infinity); this._moveCursor(+Infinity);
break; break;
@ -905,11 +905,11 @@ Interface.prototype._ttyWrite = function(s, key) {
this._moveCursor(-charLengthLeft(this.line, this.cursor)); this._moveCursor(-charLengthLeft(this.line, this.cursor));
break; break;
case 'f': // forward one character case 'f': // Forward one character
this._moveCursor(+charLengthAt(this.line, this.cursor)); this._moveCursor(+charLengthAt(this.line, this.cursor));
break; break;
case 'l': // clear the whole screen case 'l': // Clear the whole screen
cursorTo(this.output, 0, 0); cursorTo(this.output, 0, 0);
clearScreenDown(this.output); clearScreenDown(this.output);
this._refreshLine(); this._refreshLine();
@ -919,7 +919,7 @@ Interface.prototype._ttyWrite = function(s, key) {
this._historyNext(); this._historyNext();
break; break;
case 'p': // previous history item case 'p': // Previous history item
this._historyPrev(); this._historyPrev();
break; break;
@ -997,7 +997,7 @@ Interface.prototype._ttyWrite = function(s, key) {
this._sawReturnAt = 0; this._sawReturnAt = 0;
switch (key.name) { switch (key.name) {
case 'return': // carriage return, i.e. \r case 'return': // Carriage return, i.e. \r
this._sawReturnAt = Date.now(); this._sawReturnAt = Date.now();
this._line(); this._line();
break; break;

View File

@ -1016,12 +1016,12 @@ function complete(line, callback) {
if (kill.isFunction) if (kill.isFunction)
tmp[kill.line] = ''; tmp[kill.line] = '';
} }
var flat = new ArrayStream(); // make a new "input" stream var flat = new ArrayStream(); // Make a new "input" stream.
var magic = new REPLServer('', flat); // make a nested REPL var magic = new REPLServer('', flat); // Make a nested REPL.
replMap.set(magic, replMap.get(this)); replMap.set(magic, replMap.get(this));
flat.run(tmp); // eval the flattened code flat.run(tmp); // `eval` the flattened code.
// all this is only profitable if the nested REPL // All this is only profitable if the nested REPL does not have a
// does not have a bufferedCommand // bufferedCommand.
if (!magic[kBufferedCommandSymbol]) { if (!magic[kBufferedCommandSymbol]) {
magic._domain.on('error', (err) => { throw err; }); magic._domain.on('error', (err) => { throw err; });
return magic.complete(line, callback); return magic.complete(line, callback);
@ -1188,7 +1188,7 @@ function complete(line, callback) {
// https://github.com/nodejs/node/issues/2119 // https://github.com/nodejs/node/issues/2119
} }
} }
// works for non-objects // Works for non-objects
try { try {
var sentinel = 5; var sentinel = 5;
var p; var p;

View File

@ -258,7 +258,7 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
rest = rest.slice(proto.length); rest = rest.slice(proto.length);
} }
// figure out if it's got a host // Figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url // user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's // resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs. // how the browser resolves relative URLs.
@ -448,7 +448,7 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
this.pathname = '/'; this.pathname = '/';
} }
// to support http.request // To support http.request
if (this.pathname || this.search) { if (this.pathname || this.search) {
const p = this.pathname || ''; const p = this.pathname || '';
const s = this.search || ''; const s = this.search || '';
@ -746,7 +746,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
result.auth = relative.auth; result.auth = relative.auth;
result.hostname = relative.hostname || relative.host; result.hostname = relative.hostname || relative.host;
result.port = relative.port; result.port = relative.port;
// to support http.request // To support http.request
if (result.pathname || result.search) { if (result.pathname || result.search) {
var p = result.pathname || ''; var p = result.pathname || '';
var s = result.search || ''; var s = result.search || '';
@ -819,7 +819,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
result.search = relative.search; result.search = relative.search;
result.query = relative.query; result.query = relative.query;
} else if (relative.search !== null && relative.search !== undefined) { } else if (relative.search !== null && relative.search !== undefined) {
// just pull out the search. // Just pull out the search.
// like href='?foo'. // like href='?foo'.
// Put this after the other two cases because it simplifies the booleans // Put this after the other two cases because it simplifies the booleans
if (noLeadingSlashes) { if (noLeadingSlashes) {
@ -846,8 +846,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
} }
if (!srcPath.length) { if (!srcPath.length) {
// no path at all. easy. // No path at all. All other things were already handled above.
// we've already handled the other stuff above.
result.pathname = null; result.pathname = null;
// To support http.request // To support http.request
if (result.search) { if (result.search) {

View File

@ -555,7 +555,7 @@ function processCallback() {
self.push(null); self.push(null);
} }
// finished with the chunk. // Finished with the chunk.
this.buffer = null; this.buffer = null;
this.cb(); this.cb();
} }

View File

@ -38,7 +38,7 @@ const server = https.createServer(serverOptions, (req, res) => {
host: common.localhostIPv4, host: common.localhostIPv4,
port: server.address().port, port: server.address().port,
path: '/test', path: '/test',
clientCertEngine: engine, // engine will provide key+cert clientCertEngine: engine, // `engine` will provide key+cert
rejectUnauthorized: false, // Prevent failing on self-signed certificates rejectUnauthorized: false, // Prevent failing on self-signed certificates
headers: {} headers: {}
}; };

View File

@ -12,7 +12,7 @@ const initHooks = require('./init-hooks');
const util = require('util'); const util = require('util');
const sleep = util.promisify(setTimeout); const sleep = util.promisify(setTimeout);
// either 'inited' or 'resolved' // Either 'inited' or 'resolved'
const promisesInitState = new Map(); const promisesInitState = new Map();
// Either 'before' or 'after' AND asyncId must be present in the other map // Either 'before' or 'after' AND asyncId must be present in the other map
const promisesExecutionState = new Map(); const promisesExecutionState = new Map();

View File

@ -13,7 +13,7 @@ const { exec } = require('child_process');
const hooks = initHooks(); const hooks = initHooks();
hooks.enable(); hooks.enable();
const interval = setInterval(() => {}, 9999); // keep event loop open const interval = setInterval(() => {}, 9999); // Keep event loop open
process.on('SIGUSR2', common.mustCall(onsigusr2, 2)); process.on('SIGUSR2', common.mustCall(onsigusr2, 2));
let count = 0; let count = 0;
@ -35,7 +35,7 @@ function onsigusr2() {
} }
function onsigusr2Again() { function onsigusr2Again() {
clearInterval(interval); // let the event loop close clearInterval(interval); // Let the event loop close
} }
process.on('exit', onexit); process.on('exit', onexit);

View File

@ -10,16 +10,16 @@ const hooks = initHooks();
hooks.enable(); hooks.enable();
function onchange() { } function onchange() { }
// install first file watcher // Install first file watcher
fs.watchFile(__filename, onchange); fs.watchFile(__filename, onchange);
// install second file watcher // Install second file watcher
fs.watchFile(commonPath, onchange); fs.watchFile(commonPath, onchange);
// remove first file watcher // Remove first file watcher
fs.unwatchFile(__filename); fs.unwatchFile(__filename);
// remove second file watcher // Remove second file watcher
fs.unwatchFile(commonPath); fs.unwatchFile(commonPath);
process.on('exit', onexit); process.on('exit', onexit);

View File

@ -9,7 +9,7 @@ const { checkInvocations } = require('./hook-checks');
const hooks = initHooks(); const hooks = initHooks();
hooks.enable(); hooks.enable();
// install first immediate // Install first immediate
setImmediate(common.mustCall(onimmediate)); setImmediate(common.mustCall(onimmediate));
const as = hooks.activitiesOfTypes('Immediate'); const as = hooks.activitiesOfTypes('Immediate');
@ -29,7 +29,7 @@ function onimmediate() {
checkInvocations(imd1, { init: 1, before: 1 }, checkInvocations(imd1, { init: 1, before: 1 },
'imd1: when first set immediate triggered'); 'imd1: when first set immediate triggered');
// install second immediate // Install second immediate
setImmediate(common.mustCall(onimmediateTwo)); setImmediate(common.mustCall(onimmediateTwo));
as = hooks.activitiesOfTypes('Immediate'); as = hooks.activitiesOfTypes('Immediate');
assert.strictEqual(as.length, 2); assert.strictEqual(as.length, 2);

View File

@ -22,7 +22,7 @@ const hooks = initHooks();
hooks.enable(); hooks.enable();
function onchange() {} function onchange() {}
// install first file watcher // Install first file watcher
const w1 = fs.watchFile(file1, { interval: 10 }, onchange); const w1 = fs.watchFile(file1, { interval: 10 }, onchange);
let as = hooks.activitiesOfTypes('STATWATCHER'); let as = hooks.activitiesOfTypes('STATWATCHER');
@ -35,7 +35,7 @@ assert.strictEqual(statwatcher1.triggerAsyncId, 1);
checkInvocations(statwatcher1, { init: 1 }, checkInvocations(statwatcher1, { init: 1 },
'watcher1: when started to watch file'); 'watcher1: when started to watch file');
// install second file watcher // Install second file watcher
const w2 = fs.watchFile(file2, { interval: 10 }, onchange); const w2 = fs.watchFile(file2, { interval: 10 }, onchange);
as = hooks.activitiesOfTypes('STATWATCHER'); as = hooks.activitiesOfTypes('STATWATCHER');
assert.strictEqual(as.length, 2); assert.strictEqual(as.length, 2);

View File

@ -10,7 +10,7 @@ const TIMEOUT = common.platformTimeout(100);
const hooks = initHooks(); const hooks = initHooks();
hooks.enable(); hooks.enable();
// install first timeout // Install first timeout
setTimeout(common.mustCall(ontimeout), TIMEOUT); setTimeout(common.mustCall(ontimeout), TIMEOUT);
const as = hooks.activitiesOfTypes('Timeout'); const as = hooks.activitiesOfTypes('Timeout');
assert.strictEqual(as.length, 1); assert.strictEqual(as.length, 1);

View File

@ -3,7 +3,7 @@
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
// general hook test setup // General hook test setup
const tick = require('../common/tick'); const tick = require('../common/tick');
const initHooks = require('./init-hooks'); const initHooks = require('./init-hooks');
const { checkInvocations } = require('./hook-checks'); const { checkInvocations } = require('./hook-checks');

View File

@ -3,7 +3,7 @@
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
// general hook test setup // General hook test setup
const tick = require('../common/tick'); const tick = require('../common/tick');
const initHooks = require('./init-hooks'); const initHooks = require('./init-hooks');
const { checkInvocations } = require('./hook-checks'); const { checkInvocations } = require('./hook-checks');

View File

@ -795,7 +795,7 @@ module.exports = {
if (opensslCli !== null) return opensslCli; if (opensslCli !== null) return opensslCli;
if (process.config.variables.node_shared_openssl) { if (process.config.variables.node_shared_openssl) {
// use external command // Use external command
opensslCli = 'openssl'; opensslCli = 'openssl';
} else { } else {
// Use command built from sources included in Node.js repository // Use command built from sources included in Node.js repository

View File

@ -52,6 +52,6 @@ function doTest(flags, done) {
// First test the commonjs module loader // First test the commonjs module loader
doTest([], () => { doTest([], () => {
// now test the new loader // Now test the new loader
doTest(['--experimental-modules'], () => {}); doTest(['--experimental-modules'], () => {});
}); });

View File

@ -18,12 +18,12 @@ class ExtendedClass extends BaseClass {
const baseObject = new BaseClass(); const baseObject = new BaseClass();
const extendedObject = new ExtendedClass(); const extendedObject = new ExtendedClass();
// test napi_strict_equals // Test napi_strict_equals
assert.ok(test_general.testStrictEquals(val1, val1)); assert.ok(test_general.testStrictEquals(val1, val1));
assert.strictEqual(test_general.testStrictEquals(val1, val2), false); assert.strictEqual(test_general.testStrictEquals(val1, val2), false);
assert.ok(test_general.testStrictEquals(val2, val3)); assert.ok(test_general.testStrictEquals(val2, val3));
// test napi_get_prototype // Test napi_get_prototype
assert.strictEqual(test_general.testGetPrototype(baseObject), assert.strictEqual(test_general.testGetPrototype(baseObject),
Object.getPrototypeOf(baseObject)); Object.getPrototypeOf(baseObject));
assert.strictEqual(test_general.testGetPrototype(extendedObject), assert.strictEqual(test_general.testGetPrototype(extendedObject),

View File

@ -4,7 +4,7 @@ const assert = require('assert');
const test_number = require(`./build/${common.buildType}/test_number`); const test_number = require(`./build/${common.buildType}/test_number`);
// testing api calls for number // Testing api calls for number
function testNumber(num) { function testNumber(num) {
assert.strictEqual(num, test_number.Test(num)); assert.strictEqual(num, test_number.Test(num));
} }

View File

@ -2,7 +2,7 @@
const common = require('../../common'); const common = require('../../common');
const assert = require('assert'); const assert = require('assert');
// testing api calls for string // Testing api calls for string
const test_string = require(`./build/${common.buildType}/test_string`); const test_string = require(`./build/${common.buildType}/test_string`);
const empty = ''; const empty = '';

View File

@ -2,7 +2,7 @@
const common = require('../../common'); const common = require('../../common');
const assert = require('assert'); const assert = require('assert');
// testing api calls for symbol // Testing api calls for symbol
const test_symbol = require(`./build/${common.buildType}/test_symbol`); const test_symbol = require(`./build/${common.buildType}/test_symbol`);
const sym = test_symbol.New('test'); const sym = test_symbol.New('test');

View File

@ -2,7 +2,7 @@
const common = require('../../common'); const common = require('../../common');
const assert = require('assert'); const assert = require('assert');
// testing api calls for symbol // Testing api calls for symbol
const test_symbol = require(`./build/${common.buildType}/test_symbol`); const test_symbol = require(`./build/${common.buildType}/test_symbol`);
const fooSym = test_symbol.New('foo'); const fooSym = test_symbol.New('foo');

View File

@ -2,7 +2,7 @@
const common = require('../../common'); const common = require('../../common');
const assert = require('assert'); const assert = require('assert');
// testing api calls for symbol // Testing api calls for symbol
const test_symbol = require(`./build/${common.buildType}/test_symbol`); const test_symbol = require(`./build/${common.buildType}/test_symbol`);
assert.notStrictEqual(test_symbol.New(), test_symbol.New()); assert.notStrictEqual(test_symbol.New(), test_symbol.New());

View File

@ -24,5 +24,5 @@ const ctx = vm.createContext(sandbox);
const nativeKeys = vm.runInNewContext('Reflect.ownKeys(this);'); const nativeKeys = vm.runInNewContext('Reflect.ownKeys(this);');
const ownKeys = vm.runInContext('Reflect.ownKeys(this);', ctx); const ownKeys = vm.runInContext('Reflect.ownKeys(this);', ctx);
const restKeys = ownKeys.filter((key) => !nativeKeys.includes(key)); const restKeys = ownKeys.filter((key) => !nativeKeys.includes(key));
// this should not fail // This should not fail
assert.deepStrictEqual(Array.from(restKeys), ['a', 'b', sym1, sym2]); assert.deepStrictEqual(Array.from(restKeys), ['a', 'b', sym1, sym2]);

View File

@ -24,5 +24,5 @@ const ctx = vm.createContext(sandbox);
const nativeNames = vm.runInNewContext('Object.getOwnPropertyNames(this);'); const nativeNames = vm.runInNewContext('Object.getOwnPropertyNames(this);');
const ownNames = vm.runInContext('Object.getOwnPropertyNames(this);', ctx); const ownNames = vm.runInContext('Object.getOwnPropertyNames(this);', ctx);
const restNames = ownNames.filter((name) => !nativeNames.includes(name)); const restNames = ownNames.filter((name) => !nativeNames.includes(name));
// this should not fail // This should not fail
assert.deepStrictEqual(Array.from(restNames), ['a', 'b']); assert.deepStrictEqual(Array.from(restNames), ['a', 'b']);

View File

@ -24,5 +24,5 @@ const ctx = vm.createContext(sandbox);
const nativeSym = vm.runInNewContext('Object.getOwnPropertySymbols(this);'); const nativeSym = vm.runInNewContext('Object.getOwnPropertySymbols(this);');
const ownSym = vm.runInContext('Object.getOwnPropertySymbols(this);', ctx); const ownSym = vm.runInContext('Object.getOwnPropertySymbols(this);', ctx);
const restSym = ownSym.filter((sym) => !nativeSym.includes(sym)); const restSym = ownSym.filter((sym) => !nativeSym.includes(sym));
// this should not fail // This should not fail
assert.deepStrictEqual(Array.from(restSym), [sym1, sym2]); assert.deepStrictEqual(Array.from(restSym), [sym1, sym2]);

View File

@ -22,6 +22,6 @@
'use strict'; 'use strict';
require('../common'); require('../common');
// custom error throwing // Custom error throwing
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
throw ({ name: 'MyCustomError', message: 'This is a custom message' }); throw ({ name: 'MyCustomError', message: 'This is a custom message' });

View File

@ -22,6 +22,6 @@
'use strict'; 'use strict';
require('../common'); require('../common');
// custom error throwing // Custom error throwing
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
throw ({ foo: 'bar' }); throw ({ foo: 'bar' });

View File

@ -356,7 +356,7 @@ assertNotDeepOrStrict(
new Map([['1', 5], [0, 5], ['0', 5]]) new Map([['1', 5], [0, 5], ['0', 5]])
); );
// undefined value in Map // Undefined value in Map
assertDeepAndStrictEqual( assertDeepAndStrictEqual(
new Map([[1, undefined]]), new Map([[1, undefined]]),
new Map([[1, undefined]]) new Map([[1, undefined]])

View File

@ -537,7 +537,7 @@ assert.strictEqual(Buffer.from('A', 'base64').length, 0);
{ {
// test an invalid slice end. // Test an invalid slice end.
const b = Buffer.from([1, 2, 3, 4, 5]); const b = Buffer.from([1, 2, 3, 4, 5]);
const b2 = b.toString('hex', 1, 10000); const b2 = b.toString('hex', 1, 10000);
const b3 = b.toString('hex', 1, 5); const b3 = b.toString('hex', 1, 5);
@ -737,7 +737,7 @@ assert.strictEqual(x.inspect(), '<Buffer 81 a3 66 6f 6f a3 62 61 72>');
} }
{ {
// test for buffer overrun // Test for buffer overrun
const buf = Buffer.from([0, 0, 0, 0, 0]); // length: 5 const buf = Buffer.from([0, 0, 0, 0, 0]); // length: 5
const sub = buf.slice(0, 4); // length: 4 const sub = buf.slice(0, 4); // length: 4
assert.strictEqual(sub.write('12345', 'latin1'), 4); assert.strictEqual(sub.write('12345', 'latin1'), 4);
@ -747,7 +747,7 @@ assert.strictEqual(x.inspect(), '<Buffer 81 a3 66 6f 6f a3 62 61 72>');
} }
{ {
// test alloc with fill option // Test alloc with fill option
const buf = Buffer.alloc(5, '800A', 'hex'); const buf = Buffer.alloc(5, '800A', 'hex');
assert.strictEqual(buf[0], 128); assert.strictEqual(buf[0], 128);
assert.strictEqual(buf[1], 10); assert.strictEqual(buf[1], 10);

View File

@ -48,7 +48,7 @@ assert.strictEqual(a.compare(b, 0, 7, 4, 6), -1);
// zero length target // zero length target
assert.strictEqual(a.compare(b, 0, null), 1); assert.strictEqual(a.compare(b, 0, null), 1);
// coerces to targetEnd == 5 // Coerces to targetEnd == 5
assert.strictEqual(a.compare(b, 0, { valueOf: () => 5 }), -1); assert.strictEqual(a.compare(b, 0, { valueOf: () => 5 }), -1);
// zero length target // zero length target

View File

@ -128,7 +128,7 @@ common.expectsError(
} }
} }
// throw with negative sourceEnd // Throw with negative sourceEnd
common.expectsError( common.expectsError(
() => b.copy(c, 0, -1), errorProperty); () => b.copy(c, 0, -1), errorProperty);

View File

@ -88,7 +88,7 @@ assert.strictEqual(
true true
); );
// test base64 encoding // Test base64 encoding
assert.strictEqual( assert.strictEqual(
Buffer.from(b.toString('base64'), 'base64') Buffer.from(b.toString('base64'), 'base64')
.includes('ZA==', 0, 'base64'), .includes('ZA==', 0, 'base64'),
@ -112,7 +112,7 @@ assert.strictEqual(
true true
); );
// test latin1 encoding // Test latin1 encoding
assert.strictEqual( assert.strictEqual(
Buffer.from(b.toString('latin1'), 'latin1') Buffer.from(b.toString('latin1'), 'latin1')
.includes('d', 0, 'latin1'), .includes('d', 0, 'latin1'),
@ -124,7 +124,7 @@ assert.strictEqual(
true true
); );
// test binary encoding // Test binary encoding
assert.strictEqual( assert.strictEqual(
Buffer.from(b.toString('binary'), 'binary') Buffer.from(b.toString('binary'), 'binary')
.includes('d', 0, 'binary'), .includes('d', 0, 'binary'),

View File

@ -96,7 +96,7 @@ assert.strictEqual(
3 3
); );
// test base64 encoding // Test base64 encoding
assert.strictEqual( assert.strictEqual(
Buffer.from(b.toString('base64'), 'base64') Buffer.from(b.toString('base64'), 'base64')
.indexOf('ZA==', 0, 'base64'), .indexOf('ZA==', 0, 'base64'),
@ -120,7 +120,7 @@ assert.strictEqual(
3 3
); );
// test latin1 encoding // Test latin1 encoding
assert.strictEqual( assert.strictEqual(
Buffer.from(b.toString('latin1'), 'latin1') Buffer.from(b.toString('latin1'), 'latin1')
.indexOf('d', 0, 'latin1'), .indexOf('d', 0, 'latin1'),
@ -147,7 +147,7 @@ assert.strictEqual(
0 0
); );
// test binary encoding // Test binary encoding
assert.strictEqual( assert.strictEqual(
Buffer.from(b.toString('binary'), 'binary') Buffer.from(b.toString('binary'), 'binary')
.indexOf('d', 0, 'binary'), .indexOf('d', 0, 'binary'),

View File

@ -6,7 +6,7 @@ const buffer = Buffer.from([1, 2, 3, 4, 5]);
let arr; let arr;
let b; let b;
// buffers should be iterable // Buffers should be iterable
arr = []; arr = [];

View File

@ -7,7 +7,7 @@ const SlowBuffer = buffer.SlowBuffer;
const ones = [1, 1, 1, 1]; const ones = [1, 1, 1, 1];
// should create a Buffer // Should create a Buffer
let sb = SlowBuffer(4); let sb = SlowBuffer(4);
assert(sb instanceof Buffer); assert(sb instanceof Buffer);
assert.strictEqual(sb.length, 4); assert.strictEqual(sb.length, 4);
@ -19,7 +19,7 @@ for (const [key, value] of sb.entries()) {
// underlying ArrayBuffer should have the same length // underlying ArrayBuffer should have the same length
assert.strictEqual(sb.buffer.byteLength, 4); assert.strictEqual(sb.buffer.byteLength, 4);
// should work without new // Should work without new
sb = SlowBuffer(4); sb = SlowBuffer(4);
assert(sb instanceof Buffer); assert(sb instanceof Buffer);
assert.strictEqual(sb.length, 4); assert.strictEqual(sb.length, 4);
@ -28,7 +28,7 @@ for (const [key, value] of sb.entries()) {
assert.deepStrictEqual(value, ones[key]); assert.deepStrictEqual(value, ones[key]);
} }
// should work with edge cases // Should work with edge cases
assert.strictEqual(SlowBuffer(0).length, 0); assert.strictEqual(SlowBuffer(0).length, 0);
try { try {
assert.strictEqual( assert.strictEqual(

View File

@ -73,7 +73,7 @@ function typeName(value) {
}); });
} }
// test that we can call spawn // Test that we can call spawn
const child = new ChildProcess(); const child = new ChildProcess();
child.spawn({ child.spawn({
file: process.execPath, file: process.execPath,

View File

@ -80,7 +80,7 @@ if (process.argv[2] === 'child') {
// The process should also self terminate without using signals // The process should also self terminate without using signals
child.on('exit', common.mustCall()); child.on('exit', common.mustCall());
// when child is listening // When child is listening
child.on('message', function(obj) { child.on('message', function(obj) {
if (obj && obj.msg === 'ready') { if (obj && obj.msg === 'ready') {
@ -90,7 +90,7 @@ if (process.argv[2] === 'child') {
socket.on('data', function(data) { socket.on('data', function(data) {
data = data.toString(); data = data.toString();
// ready to be disconnected // Ready to be disconnected
if (data === 'ready') { if (data === 'ready') {
child.disconnect(); child.disconnect();
assert.throws( assert.throws(
@ -101,7 +101,7 @@ if (process.argv[2] === 'child') {
return; return;
} }
// disconnect is emitted // 'disconnect' is emitted
childFlag = (data === 'true'); childFlag = (data === 'true');
}); });

View File

@ -32,9 +32,9 @@ function test(fn, code) {
} }
if (common.isWindows) { if (common.isWindows) {
test(child_process.exec, 1); // exit code of cmd.exe test(child_process.exec, 1); // Exit code of cmd.exe
} else { } else {
test(child_process.exec, 127); // exit code of /bin/sh test(child_process.exec, 127); // Exit code of /bin/sh
} }
test(child_process.execFile, 'ENOENT'); test(child_process.execFile, 'ENOENT');

View File

@ -124,7 +124,7 @@ if (process.argv[2] === 'child') {
} }
} else if (msg.what === 'connection') { } else if (msg.what === 'connection') {
// child got connection // Child got connection
connections.done(); connections.done();
} else if (msg.what === 'close') { } else if (msg.what === 'close') {
child.removeListener('message', messageHandlers); child.removeListener('message', messageHandlers);

View File

@ -48,7 +48,7 @@ if (process.argv[2] === 'child') {
console.error(`[${id}] socket.end ${m}`); console.error(`[${id}] socket.end ${m}`);
}); });
// store the unfinished socket // Store the unfinished socket
if (m === 'write') { if (m === 'write') {
needEnd.push(socket); needEnd.push(socket);
} }

View File

@ -29,7 +29,7 @@ const spawnSync = require('child_process').spawnSync;
const msgOut = 'this is stdout'; const msgOut = 'this is stdout';
const msgErr = 'this is stderr'; const msgErr = 'this is stderr';
// this is actually not os.EOL? // This is actually not os.EOL?
const msgOutBuf = Buffer.from(`${msgOut}\n`); const msgOutBuf = Buffer.from(`${msgOut}\n`);
const msgErrBuf = Buffer.from(`${msgErr}\n`); const msgErrBuf = Buffer.from(`${msgErr}\n`);

View File

@ -51,6 +51,6 @@ function grandparent() {
} }
function parent() { function parent() {
// should not immediately exit. // Should not immediately exit.
spawn('cat', [], { stdio: 'inherit' }); spawn('cat', [], { stdio: 'inherit' });
} }

View File

@ -102,7 +102,7 @@ if (!id) {
})); }));
}, 2)); }, 2));
} else { } else {
assert(0); // bad command line argument assert(0); // Bad command line argument
} }
function startWorker() { function startWorker() {

View File

@ -37,7 +37,7 @@ if (cluster.isWorker) {
const servers = 2; const servers = 2;
const serverPorts = new Set(); const serverPorts = new Set();
// test a single TCP server // Test a single TCP server
const testConnection = (port, cb) => { const testConnection = (port, cb) => {
const socket = net.connect(port, '127.0.0.1', () => { const socket = net.connect(port, '127.0.0.1', () => {
// buffer result // buffer result

View File

@ -66,7 +66,7 @@ if (cluster.isMaster && process.argv.length !== 3) {
server.on('error', function(err) { server.on('error', function(err) {
// Message to child process tells it to exit // Message to child process tells it to exit
cp.send('end'); cp.send('end');
// propagate error to parent // Propagate error to parent
process.send(err); process.send(err);
}); });
})); }));

View File

@ -26,7 +26,7 @@ const cluster = require('cluster');
if (cluster.isWorker) { if (cluster.isWorker) {
// keep the worker alive // Keep the worker alive
const http = require('http'); const http = require('http');
http.Server().listen(0, '127.0.0.1'); http.Server().listen(0, '127.0.0.1');
@ -39,7 +39,7 @@ if (cluster.isWorker) {
pid: worker.process.pid pid: worker.process.pid
}); });
// terminate the cluster process // Terminate the cluster process
worker.once('listening', common.mustCall(() => { worker.once('listening', common.mustCall(() => {
setTimeout(() => { setTimeout(() => {
process.exit(0); process.exit(0);
@ -67,7 +67,7 @@ if (cluster.isWorker) {
// Make sure that the master died on purpose // Make sure that the master died on purpose
assert.strictEqual(code, 0); assert.strictEqual(code, 0);
// check worker process status // Check worker process status
const pollWorker = () => { const pollWorker = () => {
alive = common.isAlive(pid); alive = common.isAlive(pid);
if (alive) { if (alive) {

View File

@ -116,7 +116,7 @@ if (cluster.isWorker) {
}; };
} }
// some helper functions ... // Some helper functions ...
function checkResults(expected_results, results) { function checkResults(expected_results, results) {
for (const k in expected_results) { for (const k in expected_results) {

View File

@ -103,7 +103,7 @@ if (cluster.isWorker) {
}); });
} }
// some helper functions ... // Some helper functions ...
function checkResults(expected_results, results) { function checkResults(expected_results, results) {
for (const k in expected_results) { for (const k in expected_results) {

View File

@ -134,7 +134,7 @@ console.dir(custom_inspect, { showHidden: false });
console.dir({ foo: { bar: { baz: true } } }, { depth: 0 }); console.dir({ foo: { bar: { baz: true } } }, { depth: 0 });
console.dir({ foo: { bar: { baz: true } } }, { depth: 1 }); console.dir({ foo: { bar: { baz: true } } }, { depth: 1 });
// test console.dirxml() // Test console.dirxml()
console.dirxml(custom_inspect, custom_inspect); console.dirxml(custom_inspect, custom_inspect);
console.dirxml( console.dirxml(
{ foo: { bar: { baz: true } } }, { foo: { bar: { baz: true } } },
@ -142,7 +142,7 @@ console.dirxml(
{ foo: { bar: { quux: true } } } { foo: { bar: { quux: true } } }
); );
// test console.trace() // Test console.trace()
console.trace('This is a %j %d', { formatted: 'trace' }, 10, 'foo'); console.trace('This is a %j %d', { formatted: 'trace' }, 10, 'foo');
// Test console.time() and console.timeEnd() output // Test console.time() and console.timeEnd() output

View File

@ -36,7 +36,7 @@ function testCipher1(key) {
assert.strictEqual(txt, plaintext); assert.strictEqual(txt, plaintext);
// streaming cipher interface // Streaming cipher interface
// NB: In real life, it's not guaranteed that you can get all of it // NB: In real life, it's not guaranteed that you can get all of it
// in a single read() like this. But in this case, we know it's // in a single read() like this. But in this case, we know it's
// quite small, so there's no harm. // quite small, so there's no harm.

View File

@ -23,7 +23,7 @@ function testCipher1(key, iv) {
assert.strictEqual(txt, plaintext, assert.strictEqual(txt, plaintext,
`encryption/decryption with key ${key} and iv ${iv}`); `encryption/decryption with key ${key} and iv ${iv}`);
// streaming cipher interface // Streaming cipher interface
// NB: In real life, it's not guaranteed that you can get all of it // NB: In real life, it's not guaranteed that you can get all of it
// in a single read() like this. But in this case, we know it's // in a single read() like this. But in this case, we know it's
// quite small, so there's no harm. // quite small, so there's no harm.

View File

@ -230,7 +230,7 @@ if (availableCurves.has('prime256v1') && availableCurves.has('secp256k1')) {
assert(firstByte === 2 || firstByte === 3); assert(firstByte === 2 || firstByte === 3);
firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0]; firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0];
assert(firstByte === 6 || firstByte === 7); assert(firstByte === 6 || firstByte === 7);
// format value should be string // Format value should be string
common.expectsError( common.expectsError(
() => ecdh1.getPublicKey('buffer', 10), () => ecdh1.getPublicKey('buffer', 10),

View File

@ -606,7 +606,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
}); });
} }
// cipher of invalid type. // Cipher of invalid type.
for (const cipher of [0, true, {}]) { for (const cipher of [0, true, {}]) {
common.expectsError(() => generateKeyPairSync('rsa', { common.expectsError(() => generateKeyPairSync('rsa', {
modulusLength: 4096, modulusLength: 4096,

Some files were not shown because too many files have changed in this diff Show More