benchmark,doc,lib,test: capitalize comments

PR-URL: https://github.com/nodejs/node/pull/26483
Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
This commit is contained in:
Ruben Bridgewater 2019-03-07 01:03:53 +01:00
parent 01a5300f3f
commit f8763bb077
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
230 changed files with 464 additions and 467 deletions

View File

@ -65,7 +65,7 @@ function CLI(usage, settings) {
// item arguments // item arguments
this.items.push(arg); this.items.push(arg);
// the next value must be an item // The next value must be an item
mode = 'item'; mode = 'item';
} else { } else {
// Bad case, abort // Bad case, abort

View File

@ -1,4 +1,4 @@
// test the speed of .pipe() with sockets // Test the speed of .pipe() with sockets
'use strict'; 'use strict';
const common = require('../common.js'); const common = require('../common.js');
@ -78,7 +78,7 @@ Writer.prototype.write = function(chunk, encoding, cb) {
return true; return true;
}; };
// doesn't matter, never emits anything. // Doesn't matter, never emits anything.
Writer.prototype.on = function() {}; Writer.prototype.on = function() {};
Writer.prototype.once = function() {}; Writer.prototype.once = function() {};
Writer.prototype.emit = function() {}; Writer.prototype.emit = function() {};

View File

@ -1,4 +1,4 @@
// test the speed of .pipe() with sockets // Test the speed of .pipe() with sockets
'use strict'; 'use strict';
const common = require('../common.js'); const common = require('../common.js');
@ -72,7 +72,7 @@ Writer.prototype.write = function(chunk, encoding, cb) {
return true; return true;
}; };
// doesn't matter, never emits anything. // Doesn't matter, never emits anything.
Writer.prototype.on = function() {}; Writer.prototype.on = function() {};
Writer.prototype.once = function() {}; Writer.prototype.once = function() {};
Writer.prototype.emit = function() {}; Writer.prototype.emit = function() {};

View File

@ -1,4 +1,4 @@
// test the speed of .pipe() with sockets // Test the speed of .pipe() with sockets
'use strict'; 'use strict';
const common = require('../common.js'); const common = require('../common.js');
@ -75,7 +75,7 @@ Writer.prototype.write = function(chunk, encoding, cb) {
return true; return true;
}; };
// doesn't matter, never emits anything. // Doesn't matter, never emits anything.
Writer.prototype.on = function() {}; Writer.prototype.on = function() {};
Writer.prototype.once = function() {}; Writer.prototype.once = function() {};
Writer.prototype.emit = function() {}; Writer.prototype.emit = function() {};

View File

@ -1,4 +1,4 @@
// test the speed of .pipe() with sockets // Test the speed of .pipe() with sockets
'use strict'; 'use strict';
const common = require('../common.js'); const common = require('../common.js');
@ -73,7 +73,7 @@ Writer.prototype.write = function(chunk, encoding, cb) {
return true; return true;
}; };
// doesn't matter, never emits anything. // Doesn't matter, never emits anything.
Writer.prototype.on = function() {}; Writer.prototype.on = function() {};
Writer.prototype.once = function() {}; Writer.prototype.once = function() {};
Writer.prototype.emit = function() {}; Writer.prototype.emit = function() {};

View File

@ -68,7 +68,7 @@ Writer.prototype.write = function(chunk, encoding, cb) {
return true; return true;
}; };
// doesn't matter, never emits anything. // Doesn't matter, never emits anything.
Writer.prototype.on = function() {}; Writer.prototype.on = function() {};
Writer.prototype.once = function() {}; Writer.prototype.once = function() {};
Writer.prototype.emit = function() {}; Writer.prototype.emit = function() {};

View File

@ -5,9 +5,9 @@
const common = require('../common.js'); const common = require('../common.js');
const util = require('util'); const util = require('util');
// if there are dur=N and len=N args, then // If there are dur=N and len=N args, then
// run the function with those settings. // run the function with those settings.
// if not, then queue up a bunch of child processes. // If not, then queue up a bunch of child processes.
const bench = common.createBenchmark(main, { const bench = common.createBenchmark(main, {
len: [102400, 1024 * 1024 * 16], len: [102400, 1024 * 1024 * 16],
type: ['utf', 'asc', 'buf'], type: ['utf', 'asc', 'buf'],

View File

@ -50,7 +50,7 @@ if (format === 'csv') {
for (const key of Object.keys(data.conf)) { for (const key of Object.keys(data.conf)) {
conf += ` ${key}=${JSON.stringify(data.conf[key])}`; conf += ` ${key}=${JSON.stringify(data.conf[key])}`;
} }
// delete first space of the configuration // Delete first space of the configuration
conf = conf.slice(1); conf = conf.slice(1);
if (format === 'csv') { if (format === 'csv') {
// Escape quotes (") for correct csv formatting // Escape quotes (") for correct csv formatting

View File

@ -57,7 +57,7 @@ function depth1(N) {
} }
} }
// concurrent setImmediate, 0 arguments // Concurrent setImmediate, 0 arguments
function breadth(N) { function breadth(N) {
var n = 0; var n = 0;
bench.start(); bench.start();
@ -71,7 +71,7 @@ function breadth(N) {
} }
} }
// concurrent setImmediate, 1 argument // Concurrent setImmediate, 1 argument
function breadth1(N) { function breadth1(N) {
var n = 0; var n = 0;
bench.start(); bench.start();
@ -85,7 +85,7 @@ function breadth1(N) {
} }
} }
// concurrent setImmediate, 4 arguments // Concurrent setImmediate, 4 arguments
function breadth4(N) { function breadth4(N) {
N /= 2; N /= 2;
var n = 0; var n = 0;

View File

@ -237,7 +237,7 @@ if (cluster.isMaster) {
res.writeHead(200); res.writeHead(200);
res.end('hello world\n'); res.end('hello world\n');
// notify master about the request // Notify master about the request
process.send({ cmd: 'notifyRequest' }); process.send({ cmd: 'notifyRequest' });
}).listen(8000); }).listen(8000);
} }

View File

@ -27,7 +27,7 @@ server.on('listening', () => {
}); });
server.bind(41234); server.bind(41234);
// server listening 0.0.0.0:41234 // Prints: server listening 0.0.0.0:41234
``` ```
## Class: dgram.Socket ## Class: dgram.Socket
@ -172,7 +172,7 @@ server.on('listening', () => {
}); });
server.bind(41234); server.bind(41234);
// server listening 0.0.0.0:41234 // Prints: server listening 0.0.0.0:41234
``` ```
### socket.bind(options[, callback]) ### socket.bind(options[, callback])

View File

@ -420,7 +420,7 @@ d.on('error', (er) => {
}); });
d.run(() => { d.run(() => {
process.nextTick(() => { process.nextTick(() => {
setTimeout(() => { // simulating some various async stuff setTimeout(() => { // Simulating some various async stuff
fs.open('non-existent file', 'r', (er, fd) => { fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er; if (er) throw er;
// proceed... // proceed...

View File

@ -158,7 +158,7 @@ const fs = require('fs');
try { try {
fs.readFile('/some/file/that/does-not-exist', (err, data) => { fs.readFile('/some/file/that/does-not-exist', (err, data) => {
// mistaken assumption: throwing here... // Mistaken assumption: throwing here...
if (err) { if (err) {
throw err; throw err;
} }
@ -217,7 +217,7 @@ a string representing the location in the code at which
```js ```js
const myObject = {}; const myObject = {};
Error.captureStackTrace(myObject); Error.captureStackTrace(myObject);
myObject.stack; // similar to `new Error().stack` myObject.stack; // Similar to `new Error().stack`
``` ```
The first line of the trace will be prefixed with The first line of the trace will be prefixed with
@ -316,7 +316,7 @@ will not be present in the stack traces:
const cheetahify = require('./native-binding.node'); const cheetahify = require('./native-binding.node');
function makeFaster() { function makeFaster() {
// cheetahify *synchronously* calls speedy. // `cheetahify()` *synchronously* calls speedy.
cheetahify(function speedy() { cheetahify(function speedy() {
throw new Error('oh no!'); throw new Error('oh no!');
}); });

View File

@ -1911,7 +1911,7 @@ console.log(fs.readFileSync('temp.txt', 'utf8'));
// get the file descriptor of the file to be truncated // get the file descriptor of the file to be truncated
const fd = fs.openSync('temp.txt', 'r+'); const fd = fs.openSync('temp.txt', 'r+');
// truncate the file to first four bytes // Truncate the file to first four bytes
fs.ftruncate(fd, 4, (err) => { fs.ftruncate(fd, 4, (err) => {
assert.ifError(err); assert.ifError(err);
console.log(fs.readFileSync('temp.txt', 'utf8')); console.log(fs.readFileSync('temp.txt', 'utf8'));
@ -3912,7 +3912,7 @@ async function doTruncate() {
await filehandle.truncate(4); await filehandle.truncate(4);
} finally { } finally {
if (filehandle) { if (filehandle) {
// close the file if it is opened. // Close the file if it is opened.
await filehandle.close(); await filehandle.close();
} }
} }
@ -3939,7 +3939,7 @@ async function doTruncate() {
await filehandle.truncate(10); await filehandle.truncate(10);
} finally { } finally {
if (filehandle) { if (filehandle) {
// close the file if it is opened. // Close the file if it is opened.
await filehandle.close(); await filehandle.close();
} }
} }

View File

@ -373,7 +373,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
const options = { const options = {
port: 1337, port: 1337,
host: '127.0.0.1', host: '127.0.0.1',
@ -387,7 +387,7 @@ proxy.listen(1337, '127.0.0.1', () => {
req.on('connect', (res, socket, head) => { req.on('connect', (res, socket, head) => {
console.log('got connected!'); console.log('got connected!');
// make a request over an HTTP tunnel // Make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' + socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' + 'Host: www.google.com:80\r\n' +
'Connection: close\r\n' + 'Connection: close\r\n' +
@ -1313,7 +1313,7 @@ with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence. to [`response.writeHead()`][] given precedence.
```js ```js
// returns content-type = text/plain // Returns content-type = text/plain
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar'); res.setHeader('X-Foo', 'bar');
@ -1506,7 +1506,7 @@ desired with potential future retrieval and modification, use
[`response.setHeader()`][] instead. [`response.setHeader()`][] instead.
```js ```js
// returns content-type = text/plain // Returns content-type = text/plain
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar'); res.setHeader('X-Foo', 'bar');
@ -1918,7 +1918,7 @@ http.get('http://nodejs.org/dist/index.json', (res) => {
} }
if (error) { if (error) {
console.error(error.message); console.error(error.message);
// consume response data to free up memory // Consume response data to free up memory
res.resume(); res.resume();
return; return;
} }

View File

@ -3138,7 +3138,7 @@ with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence. to [`response.writeHead()`][] given precedence.
```js ```js
// returns content-type = text/plain // Returns content-type = text/plain
const server = http2.createServer((req, res) => { const server = http2.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar'); res.setHeader('X-Foo', 'bar');
@ -3332,7 +3332,7 @@ with any headers passed to [`response.writeHead()`][], with the headers passed
to [`response.writeHead()`][] given precedence. to [`response.writeHead()`][] given precedence.
```js ```js
// returns content-type = text/plain // Returns content-type = text/plain
const server = http2.createServer((req, res) => { const server = http2.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar'); res.setHeader('X-Foo', 'bar');

View File

@ -171,7 +171,7 @@ session.post('Profiler.enable', () => {
// some time later... // some time later...
session.post('Profiler.stop', (err, { profile }) => { session.post('Profiler.stop', (err, { profile }) => {
// write profile to disk, upload, etc. // Write profile to disk, upload, etc.
if (!err) { if (!err) {
fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile)); fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
} }

View File

@ -921,7 +921,7 @@ added: v10.12.0
const { createRequireFromPath } = require('module'); const { createRequireFromPath } = require('module');
const requireUtil = createRequireFromPath('../src/utils'); const requireUtil = createRequireFromPath('../src/utils');
// require `../src/utils/some-tool` // Require `../src/utils/some-tool`
requireUtil('./some-tool'); requireUtil('./some-tool');
``` ```

View File

@ -132,7 +132,7 @@ const server = net.createServer((socket) => {
throw err; throw err;
}); });
// grab an arbitrary unused port. // Grab an arbitrary unused port.
server.listen(() => { server.listen(() => {
console.log('opened server on', server.address()); console.log('opened server on', server.address());
}); });

View File

@ -331,7 +331,7 @@ const {
} = require('perf_hooks'); } = require('perf_hooks');
const obs = new PerformanceObserver((list, observer) => { const obs = new PerformanceObserver((list, observer) => {
// Called three times synchronously. list contains one item // Called three times synchronously. `list` contains one item.
}); });
obs.observe({ entryTypes: ['mark'] }); obs.observe({ entryTypes: ['mark'] });
@ -346,7 +346,7 @@ const {
} = require('perf_hooks'); } = require('perf_hooks');
const obs = new PerformanceObserver((list, observer) => { const obs = new PerformanceObserver((list, observer) => {
// called once. list contains three items // Called once. `list` contains three items.
}); });
obs.observe({ entryTypes: ['mark'], buffered: true }); obs.observe({ entryTypes: ['mark'], buffered: true });

View File

@ -1286,7 +1286,7 @@ setTimeout(() => {
// [ 1, 552 ] // [ 1, 552 ]
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// benchmark took 1000000552 nanoseconds // Benchmark took 1000000552 nanoseconds
}, 1000); }, 1000);
``` ```

View File

@ -457,7 +457,7 @@ For instance: `[[substr1, substr2, ...], originalsubstring]`.
function completer(line) { function completer(line) {
const completions = '.help .error .exit .quit .q'.split(' '); const completions = '.help .error .exit .quit .q'.split(' ');
const hits = completions.filter((c) => c.startsWith(line)); const hits = completions.filter((c) => c.startsWith(line));
// show all completions if none found // Show all completions if none found
return [hits.length ? hits : completions, line]; return [hits.length ? hits : completions, line];
} }
``` ```

View File

@ -256,8 +256,8 @@ function writeOneMillionTimes(writer, data, encoding, callback) {
// last time! // last time!
writer.write(data, encoding, callback); writer.write(data, encoding, callback);
} else { } else {
// see if we should continue, or wait // See if we should continue, or wait.
// don't pass the callback, because we're not done yet. // Don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding); ok = writer.write(data, encoding);
} }
} while (i > 0 && ok); } while (i > 0 && ok);
@ -418,7 +418,7 @@ const fs = require('fs');
const file = fs.createWriteStream('example.txt'); const file = fs.createWriteStream('example.txt');
file.write('hello, '); file.write('hello, ');
file.end('world!'); file.end('world!');
// writing more now is not allowed! // Writing more now is not allowed!
``` ```
##### writable.setDefaultEncoding(encoding) ##### writable.setDefaultEncoding(encoding)
@ -819,7 +819,7 @@ cause some amount of data to be read into an internal buffer.
```javascript ```javascript
const readable = getReadableStreamSomehow(); const readable = getReadableStreamSomehow();
readable.on('readable', function() { readable.on('readable', function() {
// there is some data to read now // There is some data to read now
let data; let data;
while (data = this.read()) { while (data = this.read()) {
@ -2431,7 +2431,7 @@ net.createServer((socket) => {
socket.end('The message was received but was not processed.\n'); socket.end('The message was received but was not processed.\n');
}); });
// start the flow of data, discarding it. // Start the flow of data, discarding it.
socket.resume(); socket.resume();
}).listen(1337); }).listen(1337);
``` ```

View File

@ -162,7 +162,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
var sockLen = freeLen + this.sockets[name].length; var sockLen = freeLen + this.sockets[name].length;
if (freeLen) { if (freeLen) {
// we have a free socket, so use that. // We have a free socket, so use that.
var socket = this.freeSockets[name].shift(); var socket = this.freeSockets[name].shift();
// Guard against an uninitialized or user supplied Socket. // Guard against an uninitialized or user supplied Socket.
if (socket._handle && typeof socket._handle.asyncReset === 'function') { if (socket._handle && typeof socket._handle.asyncReset === 'function') {
@ -357,7 +357,7 @@ function setRequestSocket(agent, req, socket) {
return; return;
} }
socket.setTimeout(req.timeout); socket.setTimeout(req.timeout);
// reset timeout after response end // Reset timeout after response end
req.once('response', (res) => { req.once('response', (res) => {
res.once('end', () => { res.once('end', () => {
if (socket.timeout !== agentTimeout) { if (socket.timeout !== agentTimeout) {

View File

@ -147,7 +147,7 @@ function parserOnMessageComplete() {
stream.push(null); stream.push(null);
} }
// force to read the next incoming message // Force to read the next incoming message
readStart(parser.socket); readStart(parser.socket);
} }

View File

@ -605,7 +605,7 @@ function resOnFinish(req, res, socket, state, server) {
state.keepAliveTimeoutSet = true; state.keepAliveTimeoutSet = true;
} }
} else { } else {
// start sending the next message // Start sending the next message
var m = state.outgoing.shift(); var m = state.outgoing.shift();
if (m) { if (m) {
m.assignSocket(socket); m.assignSocket(socket);

View File

@ -124,7 +124,7 @@ Object.defineProperty(Duplex.prototype, 'destroyed', {
return this._readableState.destroyed && this._writableState.destroyed; return this._readableState.destroyed && this._writableState.destroyed;
}, },
set(value) { set(value) {
// we ignore the value if the stream // We ignore the value if the stream
// has not been initialized yet // has not been initialized yet
if (this._readableState === undefined || if (this._readableState === undefined ||
this._writableState === undefined) { this._writableState === undefined) {

View File

@ -190,7 +190,7 @@ Object.defineProperty(Readable.prototype, 'destroyed', {
return this._readableState.destroyed; return this._readableState.destroyed;
}, },
set(value) { set(value) {
// we ignore the value if the stream // We ignore the value if the stream
// has not been initialized yet // has not been initialized yet
if (!this._readableState) { if (!this._readableState) {
return; return;
@ -600,7 +600,7 @@ function maybeReadMore_(stream, state) {
debug('maybeReadMore read 0'); debug('maybeReadMore read 0');
stream.read(0); stream.read(0);
if (len === state.length) if (len === state.length)
// didn't get any data, stop spinning. // Didn't get any data, stop spinning.
break; break;
} }
state.readingMore = false; state.readingMore = false;
@ -741,7 +741,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
src.unpipe(dest); src.unpipe(dest);
} }
// tell the dest that it's being piped to // Tell the dest that it's being piped to
dest.emit('pipe', src); dest.emit('pipe', src);
// Start the flow if it hasn't been started already. // Start the flow if it hasn't been started already.
@ -793,7 +793,7 @@ Readable.prototype.unpipe = function(dest) {
return this; return this;
} }
// slow case. multiple pipe destinations. // Slow case with multiple pipe destinations.
if (!dest) { if (!dest) {
// remove all. // remove all.
@ -896,7 +896,7 @@ function updateReadableListening(self) {
// the upcoming resume will not flow. // the upcoming resume will not flow.
state.flowing = true; state.flowing = true;
// crude way to check if we should resume // Crude way to check if we should resume
} else if (self.listenerCount('data') > 0) { } else if (self.listenerCount('data') > 0) {
self.resume(); self.resume();
} }
@ -1008,7 +1008,7 @@ Readable.prototype.wrap = function(stream) {
} }
} }
// proxy certain important events. // Proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) { for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
} }
@ -1070,7 +1070,7 @@ Object.defineProperty(Readable.prototype, 'readableFlowing', {
} }
}); });
// exposed for testing purposes only. // Exposed for testing purposes only.
Readable._fromList = fromList; Readable._fromList = fromList;
Object.defineProperty(Readable.prototype, 'readableLength', { Object.defineProperty(Readable.prototype, 'readableLength', {
@ -1096,7 +1096,7 @@ function fromList(n, state) {
if (state.objectMode) if (state.objectMode)
ret = state.buffer.shift(); ret = state.buffer.shift();
else if (!n || n >= state.length) { else if (!n || n >= state.length) {
// read it all, truncate the list // Read it all, truncate the list
if (state.decoder) if (state.decoder)
ret = state.buffer.join(''); ret = state.buffer.join('');
else if (state.buffer.length === 1) else if (state.buffer.length === 1)

View File

@ -434,7 +434,7 @@ function onwriteError(stream, state, sync, er, cb) {
cb(er); cb(er);
stream._writableState.errorEmitted = true; stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er); errorOrDestroy(stream, er);
// this can emit finish, but finish must // This can emit finish, but finish must
// always follow error // always follow error
finishMaybe(stream, state); finishMaybe(stream, state);
} }
@ -589,7 +589,7 @@ Writable.prototype.end = function(chunk, encoding, cb) {
this.uncork(); this.uncork();
} }
// ignore unnecessary end() calls. // Ignore unnecessary end() calls.
if (!state.ending) if (!state.ending)
endWritable(this, state, cb); endWritable(this, state, cb);
@ -697,7 +697,7 @@ Object.defineProperty(Writable.prototype, 'destroyed', {
return this._writableState.destroyed; return this._writableState.destroyed;
}, },
set(value) { set(value) {
// we ignore the value if the stream // We ignore the value if the stream
// has not been initialized yet // has not been initialized yet
if (!this._writableState) { if (!this._writableState) {
return; return;

View File

@ -294,7 +294,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) {
}); });
} else { } else {
if (!state.handle) if (!state.handle)
return; // handle has been closed in the mean time return; // Handle has been closed in the mean time
const err = state.handle.bind(ip, port || 0, flags); const err = state.handle.bind(ip, port || 0, flags);
if (err) { if (err) {

View File

@ -279,7 +279,7 @@ Domain.prototype.exit = function() {
var index = stack.lastIndexOf(this); var index = stack.lastIndexOf(this);
if (index === -1) return; if (index === -1) return;
// exit all domains until this one. // Exit all domains until this one.
stack.splice(index); stack.splice(index);
exports.active = stack[stack.length - 1]; exports.active = stack[stack.length - 1];
@ -294,7 +294,7 @@ Domain.prototype.add = function(ee) {
if (ee.domain === this) if (ee.domain === this)
return; return;
// has a domain already - remove it first. // Has a domain already - remove it first.
if (ee.domain) if (ee.domain)
ee.domain.remove(ee); ee.domain.remove(ee);

View File

@ -368,7 +368,7 @@ function readFileSync(path, options) {
} while (bytesRead !== 0 && pos < size); } while (bytesRead !== 0 && pos < size);
} else { } else {
do { do {
// the kernel lies about many files. // The kernel lies about many files.
// Go ahead and try to read some bytes. // Go ahead and try to read some bytes.
buffer = Buffer.allocUnsafe(8192); buffer = Buffer.allocUnsafe(8192);
bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192); bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192);
@ -1445,7 +1445,7 @@ function realpathSync(p, options) {
const knownHard = Object.create(null); const knownHard = Object.create(null);
const original = p; const original = p;
// current character position in p // Current character position in p
let pos; let pos;
// The partial path so far, including a trailing slash if any // The partial path so far, including a trailing slash if any
let current; let current;
@ -1512,7 +1512,7 @@ function realpathSync(p, options) {
continue; continue;
} }
// read the link if it wasn't read before // Read the link if it wasn't read before
// dev/ino always return 0 on windows, so skip the check. // dev/ino always return 0 on windows, so skip the check.
let linkTarget = null; let linkTarget = null;
let id; let id;
@ -1537,7 +1537,7 @@ function realpathSync(p, options) {
if (!isWindows) seenLinks[id] = linkTarget; if (!isWindows) seenLinks[id] = linkTarget;
} }
// resolve the link, then start over // Resolve the link, then start over
p = pathModule.resolve(resolvedLink, p.slice(pos)); p = pathModule.resolve(resolvedLink, p.slice(pos));
// Skip over roots // Skip over roots
@ -1585,7 +1585,7 @@ function realpath(p, options, callback) {
const seenLinks = Object.create(null); const seenLinks = Object.create(null);
const knownHard = Object.create(null); const knownHard = Object.create(null);
// current character position in p // Current character position in p
let pos; let pos;
// The partial path so far, including a trailing slash if any // The partial path so far, including a trailing slash if any
let current; let current;
@ -1611,7 +1611,7 @@ function realpath(p, options, callback) {
// Walk down the path, swapping out linked path parts for their real // Walk down the path, swapping out linked path parts for their real
// values // values
function LOOP() { function LOOP() {
// stop if scanned past end of path // Stop if scanned past end of path
if (pos >= p.length) { if (pos >= p.length) {
return callback(null, encodeRealpathResult(p, options)); return callback(null, encodeRealpathResult(p, options));
} }
@ -1651,9 +1651,9 @@ function realpath(p, options, callback) {
return process.nextTick(LOOP); return process.nextTick(LOOP);
} }
// stat & read the link if not read before // Stat & read the link if not read before.
// call gotTarget as soon as the link target is known // Call `gotTarget()` as soon as the link target is known.
// dev/ino always return 0 on windows, so skip the check. // `dev`/`ino` always return 0 on windows, so skip the check.
let id; let id;
if (!isWindows) { if (!isWindows) {
const dev = stats.dev.toString(32); const dev = stats.dev.toString(32);
@ -1680,7 +1680,7 @@ function realpath(p, options, callback) {
} }
function gotResolvedLink(resolvedLink) { function gotResolvedLink(resolvedLink) {
// resolve the link, then start over // Resolve the link, then start over
p = pathModule.resolve(resolvedLink, p.slice(pos)); p = pathModule.resolve(resolvedLink, p.slice(pos));
current = base = splitRoot(p); current = base = splitRoot(p);
pos = current.length; pos = current.length;

View File

@ -97,7 +97,7 @@ const handleConversion = {
if (!socket._handle) if (!socket._handle)
return; return;
// if the socket was created by net.Server // If the socket was created by net.Server
if (socket.server) { if (socket.server) {
// The worker should keep track of the socket // The worker should keep track of the socket
message.key = socket.server._connectionKey; message.key = socket.server._connectionKey;
@ -169,7 +169,7 @@ const handleConversion = {
// If the socket was created by net.Server we will track the socket // If the socket was created by net.Server we will track the socket
if (message.key) { if (message.key) {
// add socket to connections list // Add socket to connections list
var socketList = getSocketList('got', this, message.key); var socketList = getSocketList('got', this, message.key);
socketList.add({ socketList.add({
socket: socket socket: socket
@ -562,7 +562,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
@ -670,7 +670,7 @@ function setupChannel(target, channel) {
options = { swallowErrors: options }; options = { swallowErrors: options };
} }
// package messages with a handle object // Package messages with a handle object
if (handle) { if (handle) {
// This message will be handled by an internalMessage event handler // This message will be handled by an internalMessage event handler
message = { message = {

View File

@ -393,7 +393,7 @@ function toUnixTimestamp(time, name = 'time') {
return time; return time;
} }
if (util.isDate(time)) { if (util.isDate(time)) {
// convert to 123.456 UNIX timestamp // Convert to 123.456 UNIX timestamp
return time.getTime() / 1000; return time.getTime() / 1000;
} }
throw new ERR_INVALID_ARG_TYPE(name, ['Date', 'Time in seconds'], time); throw new ERR_INVALID_ARG_TYPE(name, ['Date', 'Time in seconds'], time);

View File

@ -118,7 +118,7 @@ function FSWatcher() {
if (this._handle !== null) { if (this._handle !== null) {
// We don't use this.close() here to avoid firing the close event. // We don't use this.close() here to avoid firing the close event.
this._handle.close(); this._handle.close();
this._handle = null; // make the handle garbage collectable this._handle = null; // Make the handle garbage collectable
} }
const error = errors.uvException({ const error = errors.uvException({
errno: status, errno: status,
@ -186,7 +186,7 @@ FSWatcher.prototype.close = function() {
return; return;
} }
this._handle.close(); this._handle.close();
this._handle = null; // make the handle garbage collectable this._handle = null; // Make the handle garbage collectable
process.nextTick(emitCloseNT, this); process.nextTick(emitCloseNT, this);
}; };

View File

@ -130,7 +130,7 @@ function onStreamEnd() {
} }
function onStreamError(error) { function onStreamError(error) {
// this is purposefully left blank // This is purposefully left blank
// //
// errors in compatibility mode are // errors in compatibility mode are
// not forwarded to the request // not forwarded to the request

View File

@ -1729,7 +1729,7 @@ class Http2Stream extends Duplex {
this.emit('timeout'); this.emit('timeout');
} }
// true if the HEADERS frame has been sent // True if the HEADERS frame has been sent
get headersSent() { get headersSent() {
return !!(this[kState].flags & STREAM_FLAGS_HEADERS_SENT); return !!(this[kState].flags & STREAM_FLAGS_HEADERS_SENT);
} }
@ -1739,7 +1739,7 @@ class Http2Stream extends Duplex {
return !!(this[kState].flags & STREAM_FLAGS_ABORTED); return !!(this[kState].flags & STREAM_FLAGS_ABORTED);
} }
// true if dealing with a HEAD request // True if dealing with a HEAD request
get headRequest() { get headRequest() {
return !!(this[kState].flags & STREAM_FLAGS_HEAD_REQUEST); return !!(this[kState].flags & STREAM_FLAGS_HEAD_REQUEST);
} }

View File

@ -341,7 +341,7 @@ Module._findPath = function(request, paths, isMain) {
} }
if (!filename) { if (!filename) {
// try it with each of the extensions // Try it with each of the extensions
if (exts === undefined) if (exts === undefined)
exts = Object.keys(Module._extensions); exts = Object.keys(Module._extensions);
filename = tryExtensions(basePath, exts, isMain); filename = tryExtensions(basePath, exts, isMain);
@ -384,7 +384,7 @@ var nmLen = nmChars.length;
if (isWindows) { if (isWindows) {
// 'from' is the __dirname of the module. // 'from' is the __dirname of the module.
Module._nodeModulePaths = function(from) { Module._nodeModulePaths = function(from) {
// guarantee that 'from' is absolute. // Guarantee that 'from' is absolute.
from = path.resolve(from); from = path.resolve(from);
// note: this approach *only* works when the path is guaranteed // note: this approach *only* works when the path is guaranteed
@ -428,7 +428,7 @@ if (isWindows) {
} else { // posix } else { // posix
// 'from' is the __dirname of the module. // 'from' is the __dirname of the module.
Module._nodeModulePaths = function(from) { Module._nodeModulePaths = function(from) {
// guarantee that 'from' is absolute. // Guarantee that 'from' is absolute.
from = path.resolve(from); from = path.resolve(from);
// Return early not only to avoid unnecessary work, but to *avoid* returning // Return early not only to avoid unnecessary work, but to *avoid* returning
// an array of two items for a root: [ '//node_modules', '/node_modules' ] // an array of two items for a root: [ '//node_modules', '/node_modules' ]
@ -850,7 +850,7 @@ Module._extensions['.node'] = function(module, filename) {
const moduleURL = pathToFileURL(filename); const moduleURL = pathToFileURL(filename);
manifest.assertIntegrity(moduleURL, content); manifest.assertIntegrity(moduleURL, content);
} }
// be aware this doesn't use `content` // Be aware this doesn't use `content`
return process.dlopen(module, path.toNamespacedPath(filename)); return process.dlopen(module, path.toNamespacedPath(filename));
}; };

View File

@ -244,7 +244,7 @@ function* emitKeys(stream) {
*/ */
const cmdStart = s.length - 1; const cmdStart = s.length - 1;
// skip one or two leading digits // Skip one or two leading digits
if (ch >= '0' && ch <= '9') { if (ch >= '0' && ch <= '9') {
s += (ch = yield); s += (ch = yield);
@ -386,7 +386,7 @@ function* emitKeys(stream) {
// carriage return // carriage return
key.name = 'return'; key.name = 'return';
} else if (ch === '\n') { } else if (ch === '\n') {
// enter, should have been called linefeed // Enter, should have been called linefeed
key.name = 'enter'; key.name = 'enter';
} else if (ch === '\t') { } else if (ch === '\t') {
// tab // tab

View File

@ -173,7 +173,7 @@ function onStreamRead(arrayBuffer) {
return stream.destroy(errnoException(nread, 'read')); return stream.destroy(errnoException(nread, 'read'));
} }
// defer this until we actually emit end // Defer this until we actually emit end
if (stream._readableState.endEmitted) { if (stream._readableState.endEmitted) {
if (stream[kMaybeDestroy]) if (stream[kMaybeDestroy])
stream[kMaybeDestroy](); stream[kMaybeDestroy]();
@ -181,7 +181,7 @@ function onStreamRead(arrayBuffer) {
if (stream[kMaybeDestroy]) if (stream[kMaybeDestroy])
stream.on('end', stream[kMaybeDestroy]); stream.on('end', stream[kMaybeDestroy]);
// push a null to signal the end of data. // Push a null to signal the end of data.
// Do it before `maybeDestroy` for correct order of events: // Do it before `maybeDestroy` for correct order of events:
// `end` -> `close` // `end` -> `close`
stream.push(null); stream.push(null);

View File

@ -85,10 +85,9 @@ const ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf({
}); });
} }
// if we have multiple next() calls // If we have multiple next() calls we will wait for the previous Promise to
// we will wait for the previous Promise to finish // finish. This logic is optimized to support for await loops, where next()
// this logic is optimized to support for await loops, // is only called once at a time.
// where next() is only called once at a time
const lastPromise = this[kLastPromise]; const lastPromise = this[kLastPromise];
let promise; let promise;
@ -96,7 +95,7 @@ const ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf({
promise = new Promise(wrapForNext(lastPromise, this)); promise = new Promise(wrapForNext(lastPromise, this));
} else { } else {
// Fast path needed to support multiple this.push() // Fast path needed to support multiple this.push()
// without triggering the next() queue // without triggering the next() queue.
const data = this[kStream].read(); const data = this[kStream].read();
if (data !== null) { if (data !== null) {
return Promise.resolve(createIterResult(data, false)); return Promise.resolve(createIterResult(data, false));
@ -136,7 +135,7 @@ 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]: {

View File

@ -510,7 +510,7 @@ Socket.prototype._read = function(n) {
debug('_read wait for connection'); debug('_read wait for connection');
this.once('connect', () => this._read(n)); this.once('connect', () => this._read(n));
} else if (!this._handle.reading) { } else if (!this._handle.reading) {
// not already reading, start the flow // Not already reading, start the flow
debug('Socket._read readStart'); debug('Socket._read readStart');
this._handle.reading = true; this._handle.reading = true;
var err = this._handle.readStart(); var err = this._handle.readStart();
@ -1024,7 +1024,7 @@ Socket.prototype.unref = function() {
function afterConnect(status, handle, req, readable, writable) { function afterConnect(status, handle, req, readable, writable) {
var self = handle[owner_symbol]; var self = handle[owner_symbol];
// callback may come after call to destroy // Callback may come after call to destroy
if (self.destroyed) { if (self.destroyed) {
return; return;
} }

View File

@ -769,7 +769,7 @@ Interface.prototype._moveCursor = function(dx) {
var newPos = this._getCursorPos(); var newPos = this._getCursorPos();
// check if cursors are in the same line // Check if cursors are in the same line
if (oldPos.rows === newPos.rows) { if (oldPos.rows === newPos.rows) {
var diffCursor = this.cursor - oldcursor; var diffCursor = this.cursor - oldcursor;
var diffWidth; var diffWidth;
@ -838,11 +838,11 @@ Interface.prototype._ttyWrite = function(s, key) {
} }
break; break;
case 'u': // delete from current to start of line case 'u': // Delete from current to start of line
this._deleteLineLeft(); this._deleteLineLeft();
break; break;
case 'k': // delete from current to end of line case 'k': // Delete from current to end of line
this._deleteLineRight(); this._deleteLineRight();
break; break;
@ -902,12 +902,12 @@ Interface.prototype._ttyWrite = function(s, key) {
} }
break; break;
case 'w': // delete backwards to a word boundary case 'w': // Delete backwards to a word boundary
case 'backspace': case 'backspace':
this._deleteWordLeft(); this._deleteWordLeft();
break; break;
case 'delete': // delete forward to a word boundary case 'delete': // Delete forward to a word boundary
this._deleteWordRight(); this._deleteWordRight();
break; break;
@ -937,7 +937,7 @@ Interface.prototype._ttyWrite = function(s, key) {
this._deleteWordRight(); this._deleteWordRight();
break; break;
case 'backspace': // delete backwards to a word boundary case 'backspace': // Delete backwards to a word boundary
this._deleteWordLeft(); this._deleteWordLeft();
break; break;
} }
@ -973,7 +973,7 @@ Interface.prototype._ttyWrite = function(s, key) {
break; break;
case 'left': case 'left':
// obtain the code point to the left // Obtain the code point to the left
this._moveCursor(-charLengthLeft(this.line, this.cursor)); this._moveCursor(-charLengthLeft(this.line, this.cursor));
break; break;

View File

@ -21,9 +21,8 @@
'use strict'; 'use strict';
// the sys module was renamed to 'util'. // The sys module was renamed to 'util'. This shim remains to keep old programs
// this shim remains to keep old programs working. // working. `sys` is deprecated and shouldn't be used.
// sys is deprecated and shouldn't be used
module.exports = require('util'); module.exports = require('util');
process.emitWarning('sys is deprecated. Use util instead.', process.emitWarning('sys is deprecated. Use util instead.',

View File

@ -80,12 +80,12 @@ const unsafeProtocol = new SafeSet([
'javascript', 'javascript',
'javascript:' 'javascript:'
]); ]);
// protocols that never have a hostname. // Protocols that never have a hostname.
const hostlessProtocol = new SafeSet([ const hostlessProtocol = new SafeSet([
'javascript', 'javascript',
'javascript:' 'javascript:'
]); ]);
// protocols that always contain a // bit. // Protocols that always contain a // bit.
const slashedProtocol = new SafeSet([ const slashedProtocol = new SafeSet([
'http', 'http',
'http:', 'http:',
@ -367,7 +367,7 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
if (this.hostname.length > hostnameMaxLen) { if (this.hostname.length > hostnameMaxLen) {
this.hostname = ''; this.hostname = '';
} else { } else {
// hostnames are always lower case. // Hostnames are always lower case.
this.hostname = this.hostname.toLowerCase(); this.hostname = this.hostname.toLowerCase();
} }
@ -396,8 +396,8 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
} }
} }
// now rest is set to the post-host stuff. // Now rest is set to the post-host stuff.
// chop off any delim chars. // Chop off any delim chars.
if (!unsafeProtocol.has(lowerProto)) { if (!unsafeProtocol.has(lowerProto)) {
// First, make 100% sure that any "autoEscape" chars get // First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they // escaped, even if encodeURIComponent doesn't think they
@ -810,7 +810,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
result.search = relative.search; result.search = relative.search;
result.query = relative.query; result.query = relative.query;
srcPath = relPath; srcPath = relPath;
// fall through to the dot-handling below. // Fall through to the dot-handling below.
} else if (relPath.length) { } else if (relPath.length) {
// it's relative // it's relative
// throw away the existing file, and take the new path instead. // throw away the existing file, and take the new path instead.

View File

@ -60,7 +60,7 @@ const {
BROTLI_OPERATION_FINISH BROTLI_OPERATION_FINISH
} = constants; } = constants;
// translation table for return codes. // Translation table for return codes.
const codes = { const codes = {
Z_OK: constants.Z_OK, Z_OK: constants.Z_OK,
Z_STREAM_END: constants.Z_STREAM_END, Z_STREAM_END: constants.Z_STREAM_END,
@ -154,8 +154,8 @@ function zlibBufferSync(engine, buffer) {
function zlibOnError(message, errno, code) { function zlibOnError(message, errno, code) {
var self = this[owner_symbol]; var self = this[owner_symbol];
// there is no way to cleanly recover. // There is no way to cleanly recover.
// continuing only obscures problems. // Continuing only obscures problems.
_close(self); _close(self);
self._hadError = true; self._hadError = true;

View File

@ -23,10 +23,10 @@ function onsigusr2() {
count++; count++;
if (count === 1) { if (count === 1) {
// trigger same signal handler again // Trigger same signal handler again
exec(`kill -USR2 ${process.pid}`); exec(`kill -USR2 ${process.pid}`);
} else { } else {
// install another signal handler // Install another signal handler
process.removeAllListeners('SIGUSR2'); process.removeAllListeners('SIGUSR2');
process.on('SIGUSR2', common.mustCall(onsigusr2Again)); process.on('SIGUSR2', common.mustCall(onsigusr2Again));

View File

@ -9,7 +9,7 @@ const p = new Promise(common.mustCall(function executor(resolve) {
resolve(5); resolve(5);
})); }));
// init hooks after promise was created // Init hooks after promise was created
const hooks = initHooks({ allowNoInit: true }); const hooks = initHooks({ allowNoInit: true });
hooks.enable(); hooks.enable();

View File

@ -42,7 +42,7 @@ function onsigusr2() {
signal1, { init: 1, before: 1 }, signal1, { init: 1, before: 1 },
' signal1: when first SIGUSR2 handler is called for the first time'); ' signal1: when first SIGUSR2 handler is called for the first time');
// trigger same signal handler again // Trigger same signal handler again
exec(`kill -USR2 ${process.pid}`); exec(`kill -USR2 ${process.pid}`);
} else { } else {
// second invocation // second invocation
@ -50,7 +50,7 @@ function onsigusr2() {
signal1, { init: 1, before: 2, after: 1 }, signal1, { init: 1, before: 2, after: 1 },
'signal1: when first SIGUSR2 handler is called for the second time'); 'signal1: when first SIGUSR2 handler is called for the second time');
// install another signal handler // Install another signal handler
process.removeAllListeners('SIGUSR2'); process.removeAllListeners('SIGUSR2');
process.on('SIGUSR2', common.mustCall(onsigusr2Again)); process.on('SIGUSR2', common.mustCall(onsigusr2Again));

View File

@ -79,7 +79,7 @@ function ontcpConnection(serverConnection) {
return; return;
} }
// only focusing on TCPCONNECTWRAP here // Only focusing on TCPCONNECTWRAP here
const tcpconnects = hooks.activitiesOfTypes('TCPCONNECTWRAP'); const tcpconnects = hooks.activitiesOfTypes('TCPCONNECTWRAP');
assert.strictEqual(tcpconnects.length, 1); assert.strictEqual(tcpconnects.length, 1);
tcpconnect = tcpconnects[0]; tcpconnect = tcpconnects[0];

View File

@ -811,7 +811,7 @@ module.exports = {
const opensslCmd = spawnSync(opensslCli, ['version']); const opensslCmd = spawnSync(opensslCli, ['version']);
if (opensslCmd.status !== 0 || opensslCmd.error !== undefined) { if (opensslCmd.status !== 0 || opensslCmd.error !== undefined) {
// openssl command cannot be executed // OpenSSL command cannot be executed
opensslCli = false; opensslCli = false;
} }
return opensslCli; return opensslCli;

View File

@ -50,7 +50,7 @@ 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

@ -167,7 +167,7 @@ if (process.argv[2] !== 'child') {
reuseAddr: true reuseAddr: true
}); });
// bind the address explicitly for sending // Bind the address explicitly for sending
// INADDR_BROADCAST to only one interface // INADDR_BROADCAST to only one interface
sendSocket.bind(common.PORT, bindAddress); sendSocket.bind(common.PORT, bindAddress);
sendSocket.on('listening', function() { sendSocket.on('listening', function() {

View File

@ -4,7 +4,7 @@
const common = require('../../common'); const common = require('../../common');
const assert = require('assert'); const assert = require('assert');
// testing api calls for function // Testing api calls for function
const test_function = require(`./build/${common.buildType}/test_function`); const test_function = require(`./build/${common.buildType}/test_function`);
function func1() { function func1() {

View File

@ -32,8 +32,7 @@ assert.strictEqual(test_general.testGetPrototype(extendedObject),
assert.notStrictEqual(test_general.testGetPrototype(baseObject), assert.notStrictEqual(test_general.testGetPrototype(baseObject),
test_general.testGetPrototype(extendedObject)); test_general.testGetPrototype(extendedObject));
// test version management functions // Test version management functions. The expected version is currently 4.
// expected version is currently 4
assert.strictEqual(test_general.testGetVersion(), 4); assert.strictEqual(test_general.testGetVersion(), 4);
[ [
@ -91,7 +90,7 @@ assert.strictEqual(finalizeWasCalled, false,
' test_general.finalizeWasCalled() ' + ' test_general.finalizeWasCalled() ' +
`returned ${finalizeWasCalled}`); `returned ${finalizeWasCalled}`);
// test napi_adjust_external_memory // Test napi_adjust_external_memory
const adjustedValue = test_general.testAdjustExternalMemory(); const adjustedValue = test_general.testAdjustExternalMemory();
assert.strictEqual(typeof adjustedValue, 'number'); assert.strictEqual(typeof adjustedValue, 'number');
assert(adjustedValue > 0); assert(adjustedValue > 0);

View File

@ -2,7 +2,7 @@
const common = require('../../common'); const common = require('../../common');
const assert = require('assert'); const assert = require('assert');
// testing handle scope api calls // Testing handle scope api calls
const testHandleScope = const testHandleScope =
require(`./build/${common.buildType}/test_handle_scope`); require(`./build/${common.buildType}/test_handle_scope`);

View File

@ -33,7 +33,7 @@ assert.ok(!propertyNames.includes('readwriteAccessor2'));
assert.ok(!propertyNames.includes('readonlyAccessor1')); assert.ok(!propertyNames.includes('readonlyAccessor1'));
assert.ok(!propertyNames.includes('readonlyAccessor2')); assert.ok(!propertyNames.includes('readonlyAccessor2'));
// validate property created with symbol // Validate property created with symbol
const start = 'Symbol('.length; const start = 'Symbol('.length;
const end = start + 'NameKeySymbol'.length; const end = start + 'NameKeySymbol'.length;
const symbolDescription = const symbolDescription =

View File

@ -29,7 +29,7 @@ if (cluster.isMaster) {
const worker2 = cluster.fork({ PRT1: msg.port1 }); const worker2 = cluster.fork({ PRT1: msg.port1 });
worker2.on('message', () => process.exit(0)); worker2.on('message', () => process.exit(0));
worker2.on('exit', (code, signal) => { worker2.on('exit', (code, signal) => {
// this is the droid we are looking for // This is the droid we are looking for
assert.strictEqual(code, 0); assert.strictEqual(code, 0);
assert.strictEqual(signal, null); assert.strictEqual(signal, null);
}); });

View File

@ -29,7 +29,7 @@ function serialFork() {
return new Promise((res) => { return new Promise((res) => {
const worker = cluster.fork(); const worker = cluster.fork();
worker.on('error', (err) => assert.fail(err)); worker.on('error', (err) => assert.fail(err));
// No common.mustCall since 1 out of 3 should fail // No common.mustCall since 1 out of 3 should fail.
worker.on('online', () => { worker.on('online', () => {
worker.on('message', common.mustCall((message) => { worker.on('message', common.mustCall((message) => {
ports.push(message.debugPort); ports.push(message.debugPort);
@ -50,10 +50,10 @@ function serialFork() {
if (cluster.isMaster) { if (cluster.isMaster) {
cluster.on('online', common.mustCall((worker) => worker.send('dbgport'), 2)); cluster.on('online', common.mustCall((worker) => worker.send('dbgport'), 2));
// Block one of the ports with a listening socket // Block one of the ports with a listening socket.
const server = net.createServer(); const server = net.createServer();
server.listen(clashPort, common.localhostIPv4, common.mustCall(() => { server.listen(clashPort, common.localhostIPv4, common.mustCall(() => {
// try to fork 3 workers No.2 should fail // Try to fork 3 workers. No.2 should fail.
Promise.all([serialFork(), serialFork(), serialFork()]) Promise.all([serialFork(), serialFork(), serialFork()])
.then(common.mustNotCall()) .then(common.mustNotCall())
.catch((err) => console.error(err)); .catch((err) => console.error(err));

View File

@ -26,7 +26,7 @@ require('../common');
console.error('before'); console.error('before');
(function() { (function() {
// these lines should contain tab! // These lines should contain tab!
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
throw ({ foo: 'bar' }); throw ({ foo: 'bar' });
})(); })();

View File

@ -9,7 +9,7 @@ function AsmModule() {
a = a | 0; a = a | 0;
b = b | 0; b = b | 0;
// should be `return (a + b) | 0;` // Should be `return (a + b) | 0;`
return a + b; return a + b;
} }

View File

@ -503,7 +503,7 @@ assertNotDeepOrStrict(
m2.set(2, 'hi'); // different order m2.set(2, 'hi'); // different order
m2.set(1, obj); m2.set(1, obj);
m2.set(3, [1, 2, 3]); // deep equal, but not reference equal. m2.set(3, [1, 2, 3]); // Deep equal, but not reference equal.
assertDeepAndStrictEqual(m1, m2); assertDeepAndStrictEqual(m1, m2);
} }

View File

@ -52,7 +52,7 @@ server.listen(
assert.strictEqual(res.statusCode, 200); assert.strictEqual(res.statusCode, 200);
res2.on('error', (err) => assert.fail(err)); res2.on('error', (err) => assert.fail(err));
res2.socket.on('error', (err) => assert.fail(err)); res2.socket.on('error', (err) => assert.fail(err));
// this should be the end of the test // This should be the end of the test
res2.destroy(); res2.destroy();
server.close(); server.close();
}) })

View File

@ -54,10 +54,10 @@ assert.strictEqual(d.length, 0);
// Test invalid encoding for Buffer.toString // Test invalid encoding for Buffer.toString
assert.throws(() => b.toString('invalid'), assert.throws(() => b.toString('invalid'),
/Unknown encoding: invalid/); /Unknown encoding: invalid/);
// invalid encoding for Buffer.write // Invalid encoding for Buffer.write
assert.throws(() => b.write('test string', 0, 5, 'invalid'), assert.throws(() => b.write('test string', 0, 5, 'invalid'),
/Unknown encoding: invalid/); /Unknown encoding: invalid/);
// unsupported arguments for Buffer.write // Unsupported arguments for Buffer.write
assert.throws(() => b.write('test', 'utf8', 0), assert.throws(() => b.write('test', 'utf8', 0),
/is no longer supported/); /is no longer supported/);
@ -87,13 +87,13 @@ const outOfRangeError = {
// Try to write a 0-length string beyond the end of b // Try to write a 0-length string beyond the end of b
common.expectsError(() => b.write('', 2048), outOfBoundsError); common.expectsError(() => b.write('', 2048), outOfBoundsError);
// throw when writing to negative offset // Throw when writing to negative offset
common.expectsError(() => b.write('a', -1), outOfBoundsError); common.expectsError(() => b.write('a', -1), outOfBoundsError);
// Throw when writing past bounds from the pool // Throw when writing past bounds from the pool
common.expectsError(() => b.write('a', 2048), outOfBoundsError); common.expectsError(() => b.write('a', 2048), outOfBoundsError);
// throw when writing to negative offset // Throw when writing to negative offset
common.expectsError(() => b.write('a', -1), outOfBoundsError); common.expectsError(() => b.write('a', -1), outOfBoundsError);
// Try to copy 0 bytes worth of data into an empty buffer // Try to copy 0 bytes worth of data into an empty buffer
@ -192,7 +192,7 @@ Buffer.alloc(1).write('', 1, 0);
} }
{ {
// also from a non-pooled instance // Also from a non-pooled instance
const b = Buffer.allocUnsafeSlow(5); const b = Buffer.allocUnsafeSlow(5);
const c = b.slice(0, 4); const c = b.slice(0, 4);
const d = c.slice(0, 2); const d = c.slice(0, 2);
@ -390,7 +390,7 @@ assert.strictEqual(Buffer.from('KioqKioqKioqKioqKioqKioqKio=',
'base64').toString(), 'base64').toString(),
'*'.repeat(20)); '*'.repeat(20));
// no padding, not a multiple of 4 // No padding, not a multiple of 4
assert.strictEqual(Buffer.from('Kg', 'base64').toString(), '*'); assert.strictEqual(Buffer.from('Kg', 'base64').toString(), '*');
assert.strictEqual(Buffer.from('Kio', 'base64').toString(), '*'.repeat(2)); assert.strictEqual(Buffer.from('Kio', 'base64').toString(), '*'.repeat(2));
assert.strictEqual(Buffer.from('KioqKg', 'base64').toString(), '*'.repeat(4)); assert.strictEqual(Buffer.from('KioqKg', 'base64').toString(), '*'.repeat(4));
@ -713,7 +713,7 @@ assert.strictEqual(x.inspect(), '<Buffer 81 a3 66 6f 6f a3 62 61 72>');
} }
{ {
// test offset returns are correct // Test offset returns are correct
const b = Buffer.allocUnsafe(16); const b = Buffer.allocUnsafe(16);
assert.strictEqual(b.writeUInt32LE(0, 0), 4); assert.strictEqual(b.writeUInt32LE(0, 0), 4);
assert.strictEqual(b.writeUInt16LE(0, 4), 6); assert.strictEqual(b.writeUInt16LE(0, 4), 6);
@ -818,7 +818,7 @@ common.expectsError(
outOfRangeError outOfRangeError
); );
// test for common write(U)IntLE/BE // Test for common write(U)IntLE/BE
{ {
let buf = Buffer.allocUnsafe(3); let buf = Buffer.allocUnsafe(3);
buf.writeUIntLE(0x123456, 0, 3); buf.writeUIntLE(0x123456, 0, 3);

View File

@ -65,7 +65,7 @@ assert.strictEqual(Buffer.byteLength(float64), 64);
const dv = new DataView(new ArrayBuffer(2)); const dv = new DataView(new ArrayBuffer(2));
assert.strictEqual(Buffer.byteLength(dv), 2); assert.strictEqual(Buffer.byteLength(dv), 2);
// special case: zero length string // Special case: zero length string
assert.strictEqual(Buffer.byteLength('', 'ascii'), 0); assert.strictEqual(Buffer.byteLength('', 'ascii'), 0);
assert.strictEqual(Buffer.byteLength('', 'HeX'), 0); assert.strictEqual(Buffer.byteLength('', 'HeX'), 0);

View File

@ -70,7 +70,7 @@ let cntr = 0;
} }
{ {
// copy starting near end of b to c // Copy starting near end of b to c
b.fill(++cntr); b.fill(++cntr);
c.fill(++cntr); c.fill(++cntr);
const copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); const copied = b.copy(c, 0, b.length - Math.floor(c.length / 2));
@ -113,7 +113,7 @@ bb.fill('hello crazy world');
// Try to copy from before the beginning of b. Should not throw. // Try to copy from before the beginning of b. Should not throw.
b.copy(c, 0, 100, 10); b.copy(c, 0, 100, 10);
// copy throws at negative sourceStart // Copy throws at negative sourceStart
common.expectsError( common.expectsError(
() => Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, -1), () => Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, -1),
errorProperty); errorProperty);

View File

@ -78,7 +78,7 @@ assert.strictEqual(b.indexOf(Buffer.from('f'), 6), -1);
assert.strictEqual(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1); assert.strictEqual(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1);
// test invalid and uppercase encoding // Test invalid and uppercase encoding
assert.strictEqual(b.indexOf('b', 'utf8'), 1); assert.strictEqual(b.indexOf('b', 'utf8'), 1);
assert.strictEqual(b.indexOf('b', 'UTF8'), 1); assert.strictEqual(b.indexOf('b', 'UTF8'), 1);
assert.strictEqual(b.indexOf('62', 'HEX'), 1); assert.strictEqual(b.indexOf('62', 'HEX'), 1);

View File

@ -16,7 +16,7 @@ for (b of buffer)
assert.deepStrictEqual(arr, [1, 2, 3, 4, 5]); assert.deepStrictEqual(arr, [1, 2, 3, 4, 5]);
// buffer iterators should be iterable // Buffer iterators should be iterable
arr = []; arr = [];

View File

@ -2,7 +2,7 @@
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
// testing basic buffer read functions // Testing basic buffer read functions
const buf = Buffer.from([0xa4, 0xfd, 0x48, 0xea, 0xcf, 0xff, 0xd9, 0x01, 0xde]); const buf = Buffer.from([0xa4, 0xfd, 0x48, 0xea, 0xcf, 0xff, 0xd9, 0x01, 0xde]);
function read(buff, funx, args, expected) { function read(buff, funx, args, expected) {

View File

@ -43,7 +43,7 @@ try {
assert.strictEqual(SlowBuffer('6').length, 6); assert.strictEqual(SlowBuffer('6').length, 6);
assert.strictEqual(SlowBuffer(true).length, 1); assert.strictEqual(SlowBuffer(true).length, 1);
// should throw with invalid length // Should throw with invalid length
const bufferMaxSizeMsg = common.expectsError({ const bufferMaxSizeMsg = common.expectsError({
code: 'ERR_INVALID_OPT_VALUE', code: 'ERR_INVALID_OPT_VALUE',
type: RangeError, type: RangeError,

View File

@ -85,7 +85,7 @@ child.spawn({
assert.strictEqual(child.hasOwnProperty('pid'), true); assert.strictEqual(child.hasOwnProperty('pid'), true);
assert(Number.isInteger(child.pid)); assert(Number.isInteger(child.pid));
// try killing with invalid signal // Try killing with invalid signal
common.expectsError( common.expectsError(
() => { child.kill('foo'); }, () => { child.kill('foo'); },
{ code: 'ERR_UNKNOWN_SIGNAL', type: TypeError } { code: 'ERR_UNKNOWN_SIGNAL', type: TypeError }

View File

@ -57,7 +57,7 @@ if (process.argv[2] === 'child') {
socket.write('ready'); socket.write('ready');
}); });
// when the server is ready tell parent // When the server is ready tell parent
server.on('listening', function() { server.on('listening', function() {
process.send({ msg: 'ready', port: server.address().port }); process.send({ msg: 'ready', port: server.address().port });
}); });

View File

@ -65,7 +65,7 @@ grep.stdin.on('drain', function(data) {
echo.stdout.resume(); echo.stdout.resume();
}); });
// propagate end from echo to grep // Propagate end from echo to grep
echo.stdout.on('end', function(code) { echo.stdout.on('end', function(code) {
grep.stdin.end(); grep.stdin.end();
}); });
@ -95,7 +95,7 @@ sed.stdin.on('drain', function(data) {
grep.stdout.resume(); grep.stdout.resume();
}); });
// propagate end from grep to sed // Propagate end from grep to sed
grep.stdout.on('end', function(code) { grep.stdout.on('end', function(code) {
console.error('grep stdout end'); console.error('grep stdout end');
sed.stdin.end(); sed.stdin.end();

View File

@ -27,7 +27,7 @@ const fork = require('child_process').fork;
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
process.send('1'); process.send('1');
// check that child don't instantly die // Check that child don't instantly die
setTimeout(function() { setTimeout(function() {
process.send('2'); process.send('2');
}, 200); }, 200);

View File

@ -56,14 +56,14 @@ function parent() {
sent += bufsize; sent += bufsize;
} while (child.stdin.write(buf)); } while (child.stdin.write(buf));
// then write a bunch more times. // Then write a bunch more times.
for (let i = 0; i < 100; i++) { for (let i = 0; i < 100; i++) {
const buf = Buffer.alloc(bufsize, '.'); const buf = Buffer.alloc(bufsize, '.');
sent += bufsize; sent += bufsize;
child.stdin.write(buf); child.stdin.write(buf);
} }
// now end, before it's all flushed. // Now end, before it's all flushed.
child.stdin.end(); child.stdin.end();
// now we wait... // now we wait...

View File

@ -45,7 +45,7 @@ function grandparent() {
child.on('close', function(code, signal) { child.on('close', function(code, signal) {
assert.strictEqual(code, 0); assert.strictEqual(code, 0);
assert.strictEqual(signal, null); assert.strictEqual(signal, null);
// cat on windows adds a \r\n at the end. // 'cat' on windows adds a \r\n at the end.
assert.strictEqual(output.trim(), input.trim()); assert.strictEqual(output.trim(), input.trim());
}); });
} }

View File

@ -11,7 +11,7 @@ const expectedError =
// Should throw if string and not ignore, pipe, or inherit // Should throw if string and not ignore, pipe, or inherit
assert.throws(() => _validateStdio('foo'), expectedError); assert.throws(() => _validateStdio('foo'), expectedError);
// should throw if not a string or array // Should throw if not a string or array
assert.throws(() => _validateStdio(600), expectedError); assert.throws(() => _validateStdio(600), expectedError);
// Should populate stdio with undefined if len < 3 // Should populate stdio with undefined if len < 3

View File

@ -25,7 +25,7 @@ syntaxArgs.forEach(function(args) {
// stderr should include '[stdin]' as the filename // stderr should include '[stdin]' as the filename
assert(c.stderr.startsWith('[stdin]'), `${c.stderr} starts with ${stdin}`); assert(c.stderr.startsWith('[stdin]'), `${c.stderr} starts with ${stdin}`);
// no stdout or stderr should be produced // No stdout or stderr should be produced
assert.strictEqual(c.stdout, ''); assert.strictEqual(c.stdout, '');
// stderr should have a syntax error message // stderr should have a syntax error message

View File

@ -18,7 +18,7 @@ syntaxArgs.forEach(function(args) {
const stdin = 'throw new Error("should not get run");'; const stdin = 'throw new Error("should not get run");';
const c = spawnSync(node, args, { encoding: 'utf8', input: stdin }); const c = spawnSync(node, args, { encoding: 'utf8', input: stdin });
// no stdout or stderr should be produced // No stdout or stderr should be produced
assert.strictEqual(c.stdout, ''); assert.strictEqual(c.stdout, '');
assert.strictEqual(c.stderr, ''); assert.strictEqual(c.stderr, '');

View File

@ -92,7 +92,7 @@ if (cluster.isWorker) {
testCluster(common.mustCall(() => { testCluster(common.mustCall(() => {
// 3. disconnect cluster // 3. disconnect cluster
cluster.disconnect(common.mustCall(() => { cluster.disconnect(common.mustCall(() => {
// run test again to confirm cleanup // Run test again to confirm cleanup
if (again) { if (again) {
test(); test();
} }

View File

@ -41,7 +41,7 @@ if (cluster.isMaster && process.argv.length !== 3) {
// Makes sure master is able to fork the worker // Makes sure master is able to fork the worker
cluster.on('fork', common.mustCall()); cluster.on('fork', common.mustCall());
// makes sure the worker is ready // Makes sure the worker is ready
worker.on('online', common.mustCall()); worker.on('online', common.mustCall());
worker.on('message', common.mustCall(function(err) { worker.on('message', common.mustCall(function(err) {
@ -71,7 +71,7 @@ if (cluster.isMaster && process.argv.length !== 3) {
}); });
})); }));
} else if (process.argv.length === 3) { } else if (process.argv.length === 3) {
// child process (of cluster.worker) // Child process (of cluster.worker)
const PIPE_NAME = process.argv[2]; const PIPE_NAME = process.argv[2];
const server = net.createServer().listen(PIPE_NAME, common.mustCall(() => { const server = net.createServer().listen(PIPE_NAME, common.mustCall(() => {

View File

@ -8,9 +8,9 @@ if (cluster.isMaster) {
cluster.fork(); cluster.fork();
cluster.on('listening', common.mustCall(function(worker, address) { cluster.on('listening', common.mustCall(function(worker, address) {
const port = address.port; const port = address.port;
// ensure that the port is not 0 or null // Ensure that the port is not 0 or null
assert(port); assert(port);
// ensure that the port is numerical // Ensure that the port is numerical
assert.strictEqual(typeof port, 'number'); assert.strictEqual(typeof port, 'number');
worker.kill(); worker.kill();
})); }));

View File

@ -26,7 +26,7 @@ const cluster = require('cluster');
const net = require('net'); const net = require('net');
if (cluster.isMaster) { if (cluster.isMaster) {
// ensure that the worker exits peacefully // Ensure that the worker exits peacefully
cluster.fork().on('exit', common.mustCall(function(statusCode) { cluster.fork().on('exit', common.mustCall(function(statusCode) {
assert.strictEqual(statusCode, 0); assert.strictEqual(statusCode, 0);
})); }));

View File

@ -26,7 +26,7 @@ const fixtures = require('../common/fixtures');
const assert = require('assert'); const assert = require('assert');
const { execFile } = require('child_process'); const { execFile } = require('child_process');
// test for leaked global detection // Test for leaked global detection
{ {
const p = fixtures.path('leakedGlobal.js'); const p = fixtures.path('leakedGlobal.js');
execFile(process.execPath, [p], common.mustCall((err, stdout, stderr) => { execFile(process.execPath, [p], common.mustCall((err, stdout, stderr) => {

View File

@ -93,35 +93,35 @@ hijackStderr(function(data) {
errStrings.push(data); errStrings.push(data);
}); });
// test console.log() goes to stdout // Test console.log() goes to stdout
console.log('foo'); console.log('foo');
console.log('foo', 'bar'); console.log('foo', 'bar');
console.log('%s %s', 'foo', 'bar', 'hop'); console.log('%s %s', 'foo', 'bar', 'hop');
console.log({ slashes: '\\\\' }); console.log({ slashes: '\\\\' });
console.log(custom_inspect); console.log(custom_inspect);
// test console.debug() goes to stdout // Test console.debug() goes to stdout
console.debug('foo'); console.debug('foo');
console.debug('foo', 'bar'); console.debug('foo', 'bar');
console.debug('%s %s', 'foo', 'bar', 'hop'); console.debug('%s %s', 'foo', 'bar', 'hop');
console.debug({ slashes: '\\\\' }); console.debug({ slashes: '\\\\' });
console.debug(custom_inspect); console.debug(custom_inspect);
// test console.info() goes to stdout // Test console.info() goes to stdout
console.info('foo'); console.info('foo');
console.info('foo', 'bar'); console.info('foo', 'bar');
console.info('%s %s', 'foo', 'bar', 'hop'); console.info('%s %s', 'foo', 'bar', 'hop');
console.info({ slashes: '\\\\' }); console.info({ slashes: '\\\\' });
console.info(custom_inspect); console.info(custom_inspect);
// test console.error() goes to stderr // Test console.error() goes to stderr
console.error('foo'); console.error('foo');
console.error('foo', 'bar'); console.error('foo', 'bar');
console.error('%s %s', 'foo', 'bar', 'hop'); console.error('%s %s', 'foo', 'bar', 'hop');
console.error({ slashes: '\\\\' }); console.error({ slashes: '\\\\' });
console.error(custom_inspect); console.error(custom_inspect);
// test console.warn() goes to stderr // Test console.warn() goes to stderr
console.warn('foo'); console.warn('foo');
console.warn('foo', 'bar'); console.warn('foo', 'bar');
console.warn('%s %s', 'foo', 'bar', 'hop'); console.warn('%s %s', 'foo', 'bar', 'hop');

View File

@ -480,8 +480,8 @@ function testCipher1(key) {
function testCipher2(key) { function testCipher2(key) {
// encryption and decryption with Base64 // Encryption and decryption with Base64.
// reported in https://github.com/joyent/node/issues/738 // Reported in https://github.com/joyent/node/issues/738
const plaintext = const plaintext =
'32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +

View File

@ -53,16 +53,16 @@ function testCipher1(key) {
function testCipher2(key) { function testCipher2(key) {
// encryption and decryption with Base64 // Encryption and decryption with Base64.
// reported in https://github.com/joyent/node/issues/738 // Reported in https://github.com/joyent/node/issues/738
const plaintext = const plaintext =
'32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +
'jAfaFg**'; 'jAfaFg**';
const cipher = crypto.createCipher('aes256', key); const cipher = crypto.createCipher('aes256', key);
// Encrypt plaintext which is in utf8 format // Encrypt plaintext which is in utf8 format to a ciphertext which will be in
// to a ciphertext which will be in Base64 // Base64.
let ciph = cipher.update(plaintext, 'utf8', 'base64'); let ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64'); ciph += cipher.final('base64');

View File

@ -36,7 +36,7 @@ const EXTERN_APEX = 0xFBEE9;
// Manually controlled string for checking binary output // Manually controlled string for checking binary output
let ucs2_control = 'a\u0000'; let ucs2_control = 'a\u0000';
// grow the strings to proper length // Grow the strings to proper length
while (ucs2_control.length <= EXTERN_APEX) { while (ucs2_control.length <= EXTERN_APEX) {
ucs2_control = ucs2_control.repeat(2); ucs2_control = ucs2_control.repeat(2);
} }

View File

@ -639,7 +639,7 @@ const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
message: 'Unknown cipher' message: 'Unknown cipher'
}); });
// cipher, but no valid passphrase. // Cipher, but no valid passphrase.
for (const passphrase of [undefined, null, 5, false, true]) { for (const passphrase of [undefined, null, 5, false, true]) {
common.expectsError(() => generateKeyPairSync('rsa', { common.expectsError(() => generateKeyPairSync('rsa', {
modulusLength: 4096, modulusLength: 4096,

View File

@ -27,7 +27,7 @@ const domain = require('domain');
const http = require('http'); const http = require('http');
const a = domain.create(); const a = domain.create();
a.enter(); // this will be our "root" domain a.enter(); // This will be our "root" domain
a.on('error', common.mustNotCall()); a.on('error', common.mustNotCall());
@ -62,11 +62,11 @@ const server = http.createServer((req, res) => {
const c = domain.create(); const c = domain.create();
const req = http.get({ host: 'localhost', port: server.address().port }); const req = http.get({ host: 'localhost', port: server.address().port });
// add the request to the C domain // Add the request to the C domain
c.add(req); c.add(req);
req.on('response', (res) => { req.on('response', (res) => {
// add the response object to the C domain // Add the response object to the C domain
c.add(res); c.add(res);
res.pipe(process.stdout); res.pipe(process.stdout);
}); });

View File

@ -60,7 +60,7 @@ const EventEmitter = require('events');
ee.emit('hello', 'a', 'b'); ee.emit('hello', 'a', 'b');
} }
// just make sure that this doesn't throw: // Just make sure that this doesn't throw:
{ {
const f = new EventEmitter(); const f = new EventEmitter();

View File

@ -62,7 +62,7 @@ function removeTestFile() {
tmpdir.refresh(); tmpdir.refresh();
// drain at 0, return false at 10. // Drain at 0, return false at 10.
const file = fs.createWriteStream(filepath, { const file = fs.createWriteStream(filepath, {
highWaterMark: 11 highWaterMark: 11
}); });

View File

@ -39,7 +39,7 @@ const data = '南越国是前203年至前111年存在于岭南地区的一个国
const tmpdir = require('../common/tmpdir'); const tmpdir = require('../common/tmpdir');
tmpdir.refresh(); tmpdir.refresh();
// Test that empty file will be created and have content added // Test that empty file will be created and have content added.
const filename = join(tmpdir.path, 'append-sync.txt'); const filename = join(tmpdir.path, 'append-sync.txt');
fs.appendFileSync(filename, data); fs.appendFileSync(filename, data);
@ -48,7 +48,7 @@ const fileData = fs.readFileSync(filename);
assert.strictEqual(Buffer.byteLength(data), fileData.length); assert.strictEqual(Buffer.byteLength(data), fileData.length);
// Test that appends data to a non empty file // Test that appends data to a non empty file.
const filename2 = join(tmpdir.path, 'append-sync2.txt'); const filename2 = join(tmpdir.path, 'append-sync2.txt');
fs.writeFileSync(filename2, currentFileData); fs.writeFileSync(filename2, currentFileData);
@ -59,7 +59,7 @@ const fileData2 = fs.readFileSync(filename2);
assert.strictEqual(Buffer.byteLength(data) + currentFileData.length, assert.strictEqual(Buffer.byteLength(data) + currentFileData.length,
fileData2.length); fileData2.length);
// Test that appendFileSync accepts buffers // Test that appendFileSync accepts buffers.
const filename3 = join(tmpdir.path, 'append-sync3.txt'); const filename3 = join(tmpdir.path, 'append-sync3.txt');
fs.writeFileSync(filename3, currentFileData); fs.writeFileSync(filename3, currentFileData);
@ -70,13 +70,13 @@ const fileData3 = fs.readFileSync(filename3);
assert.strictEqual(buf.length + currentFileData.length, fileData3.length); assert.strictEqual(buf.length + currentFileData.length, fileData3.length);
// test that appendFile accepts numbers. // Test that appendFile accepts numbers.
const filename4 = join(tmpdir.path, 'append-sync4.txt'); const filename4 = join(tmpdir.path, 'append-sync4.txt');
fs.writeFileSync(filename4, currentFileData, { mode: m }); fs.writeFileSync(filename4, currentFileData, { mode: m });
fs.appendFileSync(filename4, num, { mode: m }); fs.appendFileSync(filename4, num, { mode: m });
// windows permissions aren't unix // Windows permissions aren't Unix.
if (!common.isWindows) { if (!common.isWindows) {
const st = fs.statSync(filename4); const st = fs.statSync(filename4);
assert.strictEqual(st.mode & 0o700, m); assert.strictEqual(st.mode & 0o700, m);
@ -87,7 +87,7 @@ const fileData4 = fs.readFileSync(filename4);
assert.strictEqual(Buffer.byteLength(String(num)) + currentFileData.length, assert.strictEqual(Buffer.byteLength(String(num)) + currentFileData.length,
fileData4.length); fileData4.length);
// Test that appendFile accepts file descriptors // Test that appendFile accepts file descriptors.
const filename5 = join(tmpdir.path, 'append-sync5.txt'); const filename5 = join(tmpdir.path, 'append-sync5.txt');
fs.writeFileSync(filename5, currentFileData); fs.writeFileSync(filename5, currentFileData);
@ -100,7 +100,7 @@ const fileData5 = fs.readFileSync(filename5);
assert.strictEqual(Buffer.byteLength(data) + currentFileData.length, assert.strictEqual(Buffer.byteLength(data) + currentFileData.length,
fileData5.length); fileData5.length);
// Exit logic for cleanup // Exit logic for cleanup.
process.on('exit', function() { process.on('exit', function() {
fs.unlinkSync(filename); fs.unlinkSync(filename);

View File

@ -42,7 +42,7 @@ tmpdir.refresh();
const throwNextTick = (e) => { process.nextTick(() => { throw e; }); }; const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
// Test that empty file will be created and have content added (callback API) // Test that empty file will be created and have content added (callback API).
{ {
const filename = join(tmpdir.path, 'append.txt'); const filename = join(tmpdir.path, 'append.txt');
@ -56,7 +56,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
})); }));
} }
// Test that empty file will be created and have content added (promise API) // Test that empty file will be created and have content added (promise API).
{ {
const filename = join(tmpdir.path, 'append-promise.txt'); const filename = join(tmpdir.path, 'append-promise.txt');
@ -68,7 +68,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
.catch(throwNextTick); .catch(throwNextTick);
} }
// Test that appends data to a non-empty file (callback API) // Test that appends data to a non-empty file (callback API).
{ {
const filename = join(tmpdir.path, 'append-non-empty.txt'); const filename = join(tmpdir.path, 'append-non-empty.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -84,7 +84,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
})); }));
} }
// Test that appends data to a non-empty file (promise API) // Test that appends data to a non-empty file (promise API).
{ {
const filename = join(tmpdir.path, 'append-non-empty-promise.txt'); const filename = join(tmpdir.path, 'append-non-empty-promise.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -98,7 +98,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
.catch(throwNextTick); .catch(throwNextTick);
} }
// Test that appendFile accepts buffers (callback API) // Test that appendFile accepts buffers (callback API).
{ {
const filename = join(tmpdir.path, 'append-buffer.txt'); const filename = join(tmpdir.path, 'append-buffer.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -115,7 +115,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
})); }));
} }
// Test that appendFile accepts buffers (promises API) // Test that appendFile accepts buffers (promises API).
{ {
const filename = join(tmpdir.path, 'append-buffer-promises.txt'); const filename = join(tmpdir.path, 'append-buffer-promises.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -130,7 +130,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
.catch(throwNextTick); .catch(throwNextTick);
} }
// Test that appendFile accepts numbers (callback API) // Test that appendFile accepts numbers (callback API).
{ {
const filename = join(tmpdir.path, 'append-numbers.txt'); const filename = join(tmpdir.path, 'append-numbers.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -139,7 +139,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
fs.appendFile(filename, n, { mode: m }, common.mustCall((e) => { fs.appendFile(filename, n, { mode: m }, common.mustCall((e) => {
assert.ifError(e); assert.ifError(e);
// windows permissions aren't unix // Windows permissions aren't Unix.
if (!common.isWindows) { if (!common.isWindows) {
const st = fs.statSync(filename); const st = fs.statSync(filename);
assert.strictEqual(st.mode & 0o700, m); assert.strictEqual(st.mode & 0o700, m);
@ -153,7 +153,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
})); }));
} }
// Test that appendFile accepts numbers (promises API) // Test that appendFile accepts numbers (promises API).
{ {
const filename = join(tmpdir.path, 'append-numbers-promises.txt'); const filename = join(tmpdir.path, 'append-numbers-promises.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -161,7 +161,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
const m = 0o600; const m = 0o600;
fs.promises.appendFile(filename, n, { mode: m }) fs.promises.appendFile(filename, n, { mode: m })
.then(common.mustCall(() => { .then(common.mustCall(() => {
// windows permissions aren't unix // Windows permissions aren't Unix.
if (!common.isWindows) { if (!common.isWindows) {
const st = fs.statSync(filename); const st = fs.statSync(filename);
assert.strictEqual(st.mode & 0o700, m); assert.strictEqual(st.mode & 0o700, m);
@ -176,7 +176,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
.catch(throwNextTick); .catch(throwNextTick);
} }
// Test that appendFile accepts file descriptors (callback API) // Test that appendFile accepts file descriptors (callback API).
{ {
const filename = join(tmpdir.path, 'append-descriptors.txt'); const filename = join(tmpdir.path, 'append-descriptors.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);
@ -200,7 +200,7 @@ const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
})); }));
} }
// Test that appendFile accepts file descriptors (promises API) // Test that appendFile accepts file descriptors (promises API).
{ {
const filename = join(tmpdir.path, 'append-descriptors-promises.txt'); const filename = join(tmpdir.path, 'append-descriptors-promises.txt');
fs.writeFileSync(filename, currentFileData); fs.writeFileSync(filename, currentFileData);

View File

@ -321,7 +321,7 @@ function re(literals, ...values) {
`ENOTEMPTY: directory not empty, rename '${existingDir}' -> ` + `ENOTEMPTY: directory not empty, rename '${existingDir}' -> ` +
`'${existingDir2}'`); `'${existingDir2}'`);
assert.strictEqual(err.errno, UV_ENOTEMPTY); assert.strictEqual(err.errno, UV_ENOTEMPTY);
} else if (err.code === 'EXDEV') { // not on the same mounted filesystem } else if (err.code === 'EXDEV') { // Not on the same mounted filesystem
assert.strictEqual( assert.strictEqual(
err.message, err.message,
`EXDEV: cross-device link not permitted, rename '${existingDir}' -> ` + `EXDEV: cross-device link not permitted, rename '${existingDir}' -> ` +

View File

@ -7,7 +7,7 @@ const fs = require('fs');
const tmpdir = require('../common/tmpdir'); const tmpdir = require('../common/tmpdir');
tmpdir.refresh(); tmpdir.refresh();
// test creating and reading hard link // Test creating and reading hard link
const srcPath = path.join(tmpdir.path, 'hardlink-target.txt'); const srcPath = path.join(tmpdir.path, 'hardlink-target.txt');
const dstPath = path.join(tmpdir.path, 'link1.js'); const dstPath = path.join(tmpdir.path, 'link1.js');
fs.writeFileSync(srcPath, 'hello world'); fs.writeFileSync(srcPath, 'hello world');

View File

@ -132,7 +132,7 @@ function nextdir() {
} }
} }
// mkdirp when folder does not yet exist. // `mkdirp` when folder does not yet exist.
{ {
const pathname = path.join(tmpdir.path, nextdir(), nextdir()); const pathname = path.join(tmpdir.path, nextdir(), nextdir());

View File

@ -27,7 +27,7 @@ const fs = require('fs');
let caughtException = false; let caughtException = false;
try { try {
// should throw ENOENT, not EBADF // Should throw ENOENT, not EBADF
// see https://github.com/joyent/node/pull/1228 // see https://github.com/joyent/node/pull/1228
fs.openSync('/path/to/file/that/does/not/exist', 'r'); fs.openSync('/path/to/file/that/does/not/exist', 'r');
} catch (e) { } catch (e) {

View File

@ -17,7 +17,7 @@ tmpdir.refresh();
async function validateFilePermission() { async function validateFilePermission() {
const filePath = path.resolve(tmpDir, 'tmp-chmod.txt'); const filePath = path.resolve(tmpDir, 'tmp-chmod.txt');
const fileHandle = await open(filePath, 'w+', 0o444); const fileHandle = await open(filePath, 'w+', 0o444);
// file created with r--r--r-- 444 // File created with r--r--r-- 444
const statsBeforeMod = fs.statSync(filePath); const statsBeforeMod = fs.statSync(filePath);
assert.deepStrictEqual(statsBeforeMod.mode & 0o444, 0o444); assert.deepStrictEqual(statsBeforeMod.mode & 0o444, 0o444);
@ -34,7 +34,7 @@ async function validateFilePermission() {
expectedAccess = newPermissions; expectedAccess = newPermissions;
} }
// change the permissions to rwxr--r-x // Change the permissions to rwxr--r-x
await fileHandle.chmod(newPermissions); await fileHandle.chmod(newPermissions);
const statsAfterMod = fs.statSync(filePath); const statsAfterMod = fs.statSync(filePath);
assert.deepStrictEqual(statsAfterMod.mode & expectedAccess, expectedAccess); assert.deepStrictEqual(statsAfterMod.mode & expectedAccess, expectedAccess);

View File

@ -119,7 +119,7 @@ async function getHandle(dest) {
await unlink(dest); await unlink(dest);
} }
// bytes written to file match buffer // Bytes written to file match buffer
{ {
const handle = await getHandle(dest); const handle = await getHandle(dest);
const buf = Buffer.from('hello fsPromises'); const buf = Buffer.from('hello fsPromises');
@ -130,7 +130,7 @@ async function getHandle(dest) {
assert.deepStrictEqual(ret.buffer, buf); assert.deepStrictEqual(ret.buffer, buf);
} }
// truncate file to specified length // Truncate file to specified length
{ {
const handle = await getHandle(dest); const handle = await getHandle(dest);
const buf = Buffer.from('hello FileHandle'); const buf = Buffer.from('hello FileHandle');
@ -224,7 +224,7 @@ async function getHandle(dest) {
const newMode = 0o666; const newMode = 0o666;
if (common.isOSX) { if (common.isOSX) {
// lchmod is only available on macOS // `lchmod` is only available on macOS.
await lchmod(newLink, newMode); await lchmod(newLink, newMode);
stats = await lstat(newLink); stats = await lstat(newLink);
assert.strictEqual(stats.mode & 0o777, newMode); assert.strictEqual(stats.mode & 0o777, newMode);
@ -287,7 +287,7 @@ async function getHandle(dest) {
assert(stats.isDirectory()); assert(stats.isDirectory());
} }
// mkdirp when folder does not yet exist. // `mkdirp` when folder does not yet exist.
{ {
const dir = path.join(tmpDir, nextdir(), nextdir()); const dir = path.join(tmpDir, nextdir(), nextdir());
await mkdir(dir, { recursive: true }); await mkdir(dir, { recursive: true });
@ -344,7 +344,7 @@ async function getHandle(dest) {
}); });
} }
// mkdtemp with invalid numeric prefix // `mkdtemp` with invalid numeric prefix
{ {
await mkdtemp(path.resolve(tmpDir, 'FOO')); await mkdtemp(path.resolve(tmpDir, 'FOO'));
assert.rejects( assert.rejects(

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