doc, lib, test: do not re-require needlessly

PR-URL: https://github.com/nodejs/node/pull/14244
Reviewed-By: Alexey Orlenko <eaglexrlnk@gmail.com>
This commit is contained in:
Vse Mozhet Byt 2017-07-15 03:30:28 +03:00
parent 43bd47c352
commit 4f87522244
23 changed files with 72 additions and 85 deletions

View File

@ -1136,8 +1136,9 @@ socket to the child process. The example below spawns two children that each
handle connections with "normal" or "special" priority: handle connections with "normal" or "special" priority:
```js ```js
const normal = require('child_process').fork('child.js', ['normal']); const { fork } = require('child_process');
const special = require('child_process').fork('child.js', ['special']); const normal = fork('child.js', ['normal']);
const special = fork('child.js', ['special']);
// Open up the server and send sockets to child. Use pauseOnConnect to prevent // Open up the server and send sockets to child. Use pauseOnConnect to prevent
// the sockets from being read before they are sent to the child process. // the sockets from being read before they are sent to the child process.

View File

@ -21,14 +21,14 @@
'use strict'; 'use strict';
require('internal/util').assertCrypto(); const internalUtil = require('internal/util');
internalUtil.assertCrypto();
const assert = require('assert'); const assert = require('assert');
const Buffer = require('buffer').Buffer; const Buffer = require('buffer').Buffer;
const common = require('_tls_common'); const common = require('_tls_common');
const Connection = process.binding('crypto').Connection; const Connection = process.binding('crypto').Connection;
const EventEmitter = require('events'); const EventEmitter = require('events');
const internalUtil = require('internal/util');
const stream = require('stream'); const stream = require('stream');
const Timer = process.binding('timer_wrap').Timer; const Timer = process.binding('timer_wrap').Timer;
const tls = require('tls'); const tls = require('tls');

View File

@ -1,6 +1,7 @@
'use strict'; 'use strict';
const errors = require('internal/errors'); const errors = require('internal/errors');
const util = require('util');
const constants = process.binding('constants').os.signals; const constants = process.binding('constants').os.signals;
const assert = process.assert = function(x, msg) { const assert = process.assert = function(x, msg) {
@ -178,10 +179,8 @@ function setupKillAndExit() {
} }
} }
if (err) { if (err)
const errnoException = require('util')._errnoException; throw util._errnoException(err, 'kill');
throw errnoException(err, 'kill');
}
return true; return true;
}; };
@ -212,8 +211,7 @@ function setupSignalHandlers() {
const err = wrap.start(signum); const err = wrap.start(signum);
if (err) { if (err) {
wrap.close(); wrap.close();
const errnoException = require('util')._errnoException; throw util._errnoException(err, 'uv_signal_start');
throw errnoException(err, 'uv_signal_start');
} }
signalWraps[type] = wrap; signalWraps[type] = wrap;
@ -253,10 +251,9 @@ function setupChannel() {
function setupRawDebug() { function setupRawDebug() {
const format = require('util').format;
const rawDebug = process._rawDebug; const rawDebug = process._rawDebug;
process._rawDebug = function() { process._rawDebug = function() {
rawDebug(format.apply(null, arguments)); rawDebug(util.format.apply(null, arguments));
}; };
} }

View File

@ -86,7 +86,7 @@ try {
} }
// hack for repl require to work properly with node_modules folders // hack for repl require to work properly with node_modules folders
module.paths = require('module')._nodeModulePaths(module.filename); module.paths = Module._nodeModulePaths(module.filename);
// If obj.hasOwnProperty has been overridden, then calling // If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break. // obj.hasOwnProperty(prop) will break.
@ -794,7 +794,7 @@ function complete(line, callback) {
filter = match[1]; filter = match[1];
var dir, files, f, name, base, ext, abs, subfiles, s; var dir, files, f, name, base, ext, abs, subfiles, s;
group = []; group = [];
var paths = module.paths.concat(require('module').globalPaths); var paths = module.paths.concat(Module.globalPaths);
for (i = 0; i < paths.length; i++) { for (i = 0; i < paths.length; i++) {
dir = path.resolve(paths[i], subdir); dir = path.resolve(paths[i], subdir);
try { try {

View File

@ -25,11 +25,10 @@ const path = require('path');
const fs = require('fs'); const fs = require('fs');
const assert = require('assert'); const assert = require('assert');
const os = require('os'); const os = require('os');
const child_process = require('child_process'); const { exec, execSync, spawn, spawnSync } = require('child_process');
const stream = require('stream'); const stream = require('stream');
const util = require('util'); const util = require('util');
const Timer = process.binding('timer_wrap').Timer; const Timer = process.binding('timer_wrap').Timer;
const execSync = require('child_process').execSync;
const testRoot = process.env.NODE_TEST_DIR ? const testRoot = process.env.NODE_TEST_DIR ?
fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..'); fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..');
@ -186,7 +185,7 @@ Object.defineProperty(exports, 'inFreeBSDJail', {
if (inFreeBSDJail !== null) return inFreeBSDJail; if (inFreeBSDJail !== null) return inFreeBSDJail;
if (exports.isFreeBSD && if (exports.isFreeBSD &&
child_process.execSync('sysctl -n security.jail.jailed').toString() === execSync('sysctl -n security.jail.jailed').toString() ===
'1\n') { '1\n') {
inFreeBSDJail = true; inFreeBSDJail = true;
} else { } else {
@ -233,7 +232,7 @@ Object.defineProperty(exports, 'opensslCli', {get: function() {
if (exports.isWindows) opensslCli += '.exe'; if (exports.isWindows) opensslCli += '.exe';
const opensslCmd = child_process.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;
@ -283,7 +282,7 @@ exports.childShouldThrowAndAbort = function() {
} }
testCmd += `"${process.argv[0]}" --abort-on-uncaught-exception `; testCmd += `"${process.argv[0]}" --abort-on-uncaught-exception `;
testCmd += `"${process.argv[1]}" child`; testCmd += `"${process.argv[1]}" child`;
const child = child_process.exec(testCmd); const child = exec(testCmd);
child.on('exit', function onExit(exitCode, signal) { child.on('exit', function onExit(exitCode, signal) {
const errMsg = 'Test should have aborted ' + const errMsg = 'Test should have aborted ' +
`but instead exited with exit code ${exitCode}` + `but instead exited with exit code ${exitCode}` +
@ -303,8 +302,6 @@ exports.ddCommand = function(filename, kilobytes) {
exports.spawnPwd = function(options) { exports.spawnPwd = function(options) {
const spawn = require('child_process').spawn;
if (exports.isWindows) { if (exports.isWindows) {
return spawn('cmd.exe', ['/d', '/c', 'cd'], options); return spawn('cmd.exe', ['/d', '/c', 'cd'], options);
} else { } else {
@ -314,8 +311,6 @@ exports.spawnPwd = function(options) {
exports.spawnSyncPwd = function(options) { exports.spawnSyncPwd = function(options) {
const spawnSync = require('child_process').spawnSync;
if (exports.isWindows) { if (exports.isWindows) {
return spawnSync('cmd.exe', ['/d', '/c', 'cd'], options); return spawnSync('cmd.exe', ['/d', '/c', 'cd'], options);
} else { } else {
@ -789,7 +784,7 @@ exports.getTTYfd = function getTTYfd() {
else if (!tty.isatty(tty_fd)) tty_fd++; else if (!tty.isatty(tty_fd)) tty_fd++;
else { else {
try { try {
tty_fd = require('fs').openSync('/dev/tty'); tty_fd = fs.openSync('/dev/tty');
} catch (e) { } catch (e) {
// There aren't any tty fd's available to use. // There aren't any tty fd's available to use.
return -1; return -1;

View File

@ -2,7 +2,6 @@
require('../common'); require('../common');
const assert = require('assert'); const assert = require('assert');
const a = require('assert');
function makeBlock(f) { function makeBlock(f) {
const args = Array.prototype.slice.call(arguments, 1); const args = Array.prototype.slice.call(arguments, 1);
@ -51,7 +50,8 @@ equalArrayPairs.forEach((arrayPair) => {
notEqualArrayPairs.forEach((arrayPair) => { notEqualArrayPairs.forEach((arrayPair) => {
assert.throws( assert.throws(
makeBlock(a.deepEqual, arrayPair[0], arrayPair[1]), // eslint-disable-next-line no-restricted-properties
a.AssertionError makeBlock(assert.deepEqual, arrayPair[0], arrayPair[1]),
assert.AssertionError
); );
}); });

View File

@ -22,7 +22,7 @@
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const a = require('assert'); const a = assert;
function makeBlock(f) { function makeBlock(f) {
const args = Array.prototype.slice.call(arguments, 1); const args = Array.prototype.slice.call(arguments, 1);

View File

@ -22,8 +22,7 @@
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const spawn = require('child_process').spawn; const { fork, spawn } = require('child_process');
const fork = require('child_process').fork;
// Fork, then spawn. The spawned process should not hang. // Fork, then spawn. The spawned process should not hang.
switch (process.argv[2] || '') { switch (process.argv[2] || '') {

View File

@ -3,8 +3,7 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const path = require('path'); const path = require('path');
const net = require('net'); const net = require('net');
const fork = require('child_process').fork; const { fork, spawn } = require('child_process');
const spawn = require('child_process').spawn;
const emptyFile = path.join(common.fixturesDir, 'empty.js'); const emptyFile = path.join(common.fixturesDir, 'empty.js');

View File

@ -148,6 +148,8 @@ const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
bufferTooSmall: /^RangeError: buffer too small$/, bufferTooSmall: /^RangeError: buffer too small$/,
}; };
const max = require('buffer').kMaxLength + 1;
for (const buf of bufs) { for (const buf of bufs) {
const len = Buffer.byteLength(buf); const len = Buffer.byteLength(buf);
assert.strictEqual(len, 10, `Expected byteLength of 10, got ${len}`); assert.strictEqual(len, 10, `Expected byteLength of 10, got ${len}`);
@ -168,8 +170,6 @@ const expectedErrorRegexp = /^TypeError: size must be a number >= 0$/;
crypto.randomFill(buf, NaN, common.mustNotCall()); crypto.randomFill(buf, NaN, common.mustNotCall());
}, errMessages.offsetNotNumber); }, errMessages.offsetNotNumber);
const max = require('buffer').kMaxLength + 1;
assert.throws(() => { assert.throws(() => {
crypto.randomFillSync(buf, 11); crypto.randomFillSync(buf, 11);
}, errMessages.offsetOutOfRange); }, errMessages.offsetOutOfRange);

View File

@ -20,7 +20,6 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
require('../common');
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const domain = require('domain'); const domain = require('domain');

View File

@ -24,9 +24,10 @@ const strictEqual = require('assert').strictEqual;
} }
const dgram = require('dgram');
// dgram ipv4 // dgram ipv4
{ {
const dgram = require('dgram');
const sock4 = dgram.createSocket('udp4'); const sock4 = dgram.createSocket('udp4');
strictEqual(Object.getPrototypeOf(sock4._handle).hasOwnProperty('hasRef'), strictEqual(Object.getPrototypeOf(sock4._handle).hasOwnProperty('hasRef'),
true, 'udp_wrap: ipv4: hasRef() missing'); true, 'udp_wrap: ipv4: hasRef() missing');
@ -46,7 +47,6 @@ const strictEqual = require('assert').strictEqual;
// dgram ipv6 // dgram ipv6
{ {
const dgram = require('dgram');
const sock6 = dgram.createSocket('udp6'); const sock6 = dgram.createSocket('udp6');
strictEqual(Object.getPrototypeOf(sock6._handle).hasOwnProperty('hasRef'), strictEqual(Object.getPrototypeOf(sock6._handle).hasOwnProperty('hasRef'),
true, 'udp_wrap: ipv6: hasRef() missing'); true, 'udp_wrap: ipv6: hasRef() missing');

View File

@ -2,8 +2,7 @@
require('../common'); require('../common');
const assert = require('assert'); const assert = require('assert');
const inspect = require('util').inspect; const inspect = require('util').inspect;
const checkIsHttpToken = require('_http_common')._checkIsHttpToken; const { _checkIsHttpToken, _checkInvalidHeaderChar } = require('_http_common');
const checkInvalidHeaderChar = require('_http_common')._checkInvalidHeaderChar;
// Good header field names // Good header field names
[ [
@ -29,8 +28,8 @@ const checkInvalidHeaderChar = require('_http_common')._checkInvalidHeaderChar;
'3.14159265359' '3.14159265359'
].forEach(function(str) { ].forEach(function(str) {
assert.strictEqual( assert.strictEqual(
checkIsHttpToken(str), true, _checkIsHttpToken(str), true,
`checkIsHttpToken(${inspect(str)}) unexpectedly failed`); `_checkIsHttpToken(${inspect(str)}) unexpectedly failed`);
}); });
// Bad header field names // Bad header field names
[ [
@ -55,8 +54,8 @@ const checkInvalidHeaderChar = require('_http_common')._checkInvalidHeaderChar;
'This,That' 'This,That'
].forEach(function(str) { ].forEach(function(str) {
assert.strictEqual( assert.strictEqual(
checkIsHttpToken(str), false, _checkIsHttpToken(str), false,
`checkIsHttpToken(${inspect(str)}) unexpectedly succeeded`); `_checkIsHttpToken(${inspect(str)}) unexpectedly succeeded`);
}); });
@ -68,8 +67,8 @@ const checkInvalidHeaderChar = require('_http_common')._checkInvalidHeaderChar;
'!@#$%^&*()-_=+\\;\':"[]{}<>,./?|~`' '!@#$%^&*()-_=+\\;\':"[]{}<>,./?|~`'
].forEach(function(str) { ].forEach(function(str) {
assert.strictEqual( assert.strictEqual(
checkInvalidHeaderChar(str), false, _checkInvalidHeaderChar(str), false,
`checkInvalidHeaderChar(${inspect(str)}) unexpectedly failed`); `_checkInvalidHeaderChar(${inspect(str)}) unexpectedly failed`);
}); });
// Bad header field values // Bad header field values
@ -84,6 +83,6 @@ const checkInvalidHeaderChar = require('_http_common')._checkInvalidHeaderChar;
'Ding!\x07' 'Ding!\x07'
].forEach(function(str) { ].forEach(function(str) {
assert.strictEqual( assert.strictEqual(
checkInvalidHeaderChar(str), true, _checkInvalidHeaderChar(str), true,
`checkInvalidHeaderChar(${inspect(str)}) unexpectedly succeeded`); `_checkInvalidHeaderChar(${inspect(str)}) unexpectedly succeeded`);
}); });

View File

@ -85,7 +85,6 @@ function parent() {
}).listen(0, function() { }).listen(0, function() {
console.error('server listening on %d', this.address().port); console.error('server listening on %d', this.address().port);
const spawn = require('child_process').spawn;
const child = spawn(process.execPath, [__filename, 'child'], { const child = spawn(process.execPath, [__filename, 'child'], {
stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], stdio: [ 'ignore', 'ignore', 'ignore', server._handle ],
detached: true detached: true

View File

@ -40,27 +40,27 @@ const server = net.createServer(function(conn) {
server.listen(0, function() { server.listen(0, function() {
// Client 1 // Client 1
conn = require('net').createConnection(this.address().port, 'localhost'); conn = net.createConnection(this.address().port, 'localhost');
conn.resume(); conn.resume();
conn.on('data', onDataOk); conn.on('data', onDataOk);
// Client 2 // Client 2
conn = require('net').createConnection(this.address().port, 'localhost'); conn = net.createConnection(this.address().port, 'localhost');
conn.pause(); conn.pause();
conn.resume(); conn.resume();
conn.on('data', onDataOk); conn.on('data', onDataOk);
// Client 3 // Client 3
conn = require('net').createConnection(this.address().port, 'localhost'); conn = net.createConnection(this.address().port, 'localhost');
conn.pause(); conn.pause();
conn.on('data', common.mustNotCall()); conn.on('data', common.mustNotCall());
scheduleTearDown(conn); scheduleTearDown(conn);
// Client 4 // Client 4
conn = require('net').createConnection(this.address().port, 'localhost'); conn = net.createConnection(this.address().port, 'localhost');
conn.resume(); conn.resume();
conn.pause(); conn.pause();
conn.resume(); conn.resume();
@ -68,7 +68,7 @@ server.listen(0, function() {
// Client 5 // Client 5
conn = require('net').createConnection(this.address().port, 'localhost'); conn = net.createConnection(this.address().port, 'localhost');
conn.resume(); conn.resume();
conn.resume(); conn.resume();
conn.pause(); conn.pause();

View File

@ -83,22 +83,23 @@ function child5() {
} }
function parent() { function parent() {
const { spawn } = require('child_process');
const node = process.execPath;
const f = __filename;
const option = { stdio: [ 0, 1, 'ignore' ] };
const test = (arg, exit) => {
spawn(node, [f, arg], option).on('exit', (code) => {
assert.strictEqual(
code, exit,
`wrong exit for ${arg}\nexpected:${exit} but got:${code}`);
console.log('ok - %s exited with %d', arg, exit);
});
};
test('child1', 42); test('child1', 42);
test('child2', 42); test('child2', 42);
test('child3', 0); test('child3', 0);
test('child4', 1); test('child4', 1);
test('child5', 99); test('child5', 99);
} }
function test(arg, exit) {
const spawn = require('child_process').spawn;
const node = process.execPath;
const f = __filename;
const option = { stdio: [ 0, 1, 'ignore' ] };
spawn(node, [f, arg], option).on('exit', function(code) {
assert.strictEqual(
code, exit,
`wrong exit for ${arg}\nexpected:${exit} but got:${code}`);
console.log('ok - %s exited with %d', arg, exit);
});
}

View File

@ -27,8 +27,7 @@ const readline = require('readline');
const internalReadline = require('internal/readline'); const internalReadline = require('internal/readline');
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
const inherits = require('util').inherits; const inherits = require('util').inherits;
const Writable = require('stream').Writable; const { Writable, Readable } = require('stream');
const Readable = require('stream').Readable;
function FakeInput() { function FakeInput() {
EventEmitter.call(this); EventEmitter.call(this);

View File

@ -4,8 +4,7 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const exec = require('child_process').exec; const { exec, spawn } = require('child_process');
const spawn = require('child_process').spawn;
const util = require('util'); const util = require('util');
common.refreshTmpDir(); common.refreshTmpDir();

View File

@ -21,9 +21,8 @@
'use strict'; 'use strict';
require('../common'); require('../common');
const Readable = require('stream').Readable;
const Writable = require('stream').Writable;
const assert = require('assert'); const assert = require('assert');
const { Readable, Writable } = require('stream');
const EE = require('events').EventEmitter; const EE = require('events').EventEmitter;

View File

@ -28,6 +28,15 @@ if (!common.opensslCli)
if (!common.hasCrypto) if (!common.hasCrypto)
common.skip('missing crypto'); common.skip('missing crypto');
const assert = require('assert');
const tls = require('tls');
const fs = require('fs');
const { join } = require('path');
const { spawn } = require('child_process');
const keyFile = join(common.fixturesDir, 'agent.key');
const certFile = join(common.fixturesDir, 'agent.crt');
doTest({ tickets: false }, function() { doTest({ tickets: false }, function() {
doTest({ tickets: true }, function() { doTest({ tickets: true }, function() {
doTest({ tickets: false, invalidSession: true }, function() { doTest({ tickets: false, invalidSession: true }, function() {
@ -37,14 +46,6 @@ doTest({ tickets: false }, function() {
}); });
function doTest(testOptions, callback) { function doTest(testOptions, callback) {
const assert = require('assert');
const tls = require('tls');
const fs = require('fs');
const join = require('path').join;
const spawn = require('child_process').spawn;
const keyFile = join(common.fixturesDir, 'agent.key');
const certFile = join(common.fixturesDir, 'agent.crt');
const key = fs.readFileSync(keyFile); const key = fs.readFileSync(keyFile);
const cert = fs.readFileSync(certFile); const cert = fs.readFileSync(certFile);
const options = { const options = {

View File

@ -24,6 +24,7 @@
require('../common'); require('../common');
const assert = require('assert'); const assert = require('assert');
const vm = require('vm');
const start = Date.now(); const start = Date.now();
let maxMem = 0; let maxMem = 0;
@ -35,7 +36,7 @@ assert(ok, 'Run this test with --max_old_space_size=32.');
const interval = setInterval(function() { const interval = setInterval(function() {
try { try {
require('vm').runInNewContext('throw 1;'); vm.runInNewContext('throw 1;');
} catch (e) { } catch (e) {
} }
@ -52,7 +53,7 @@ const interval = setInterval(function() {
function testContextLeak() { function testContextLeak() {
for (let i = 0; i < 1000; i++) for (let i = 0; i < 1000; i++)
require('vm').createContext({}); vm.createContext({});
} }
process.on('exit', function() { process.on('exit', function() {

View File

@ -23,8 +23,7 @@
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const execSync = require('child_process').execSync; const { execFileSync, execSync } = require('child_process');
const execFileSync = require('child_process').execFileSync;
const TIMER = 200; const TIMER = 200;
const SLEEP = 2000; const SLEEP = 2000;

View File

@ -146,7 +146,7 @@ try {
assert.strictEqual(e.message, 'blah'); assert.strictEqual(e.message, 'blah');
} }
assert.strictEqual(require('path').dirname(__filename), __dirname); assert.strictEqual(path.dirname(__filename), __dirname);
console.error('load custom file types with extensions'); console.error('load custom file types with extensions');
require.extensions['.test'] = function(module, filename) { require.extensions['.test'] = function(module, filename) {