-
diff --git a/lib/_debugger.js b/lib/_debugger.js
index ad7ee6295bee2a..a4638048ea41f5 100644
--- a/lib/_debugger.js
+++ b/lib/_debugger.js
@@ -25,8 +25,8 @@ exports.start = function(argv, stdin, stdout) {
stdin = stdin || process.stdin;
stdout = stdout || process.stdout;
- var args = ['--debug-brk'].concat(argv),
- interface_ = new Interface(stdin, stdout, args);
+ const args = ['--debug-brk'].concat(argv);
+ const interface_ = new Interface(stdin, stdout, args);
stdin.resume();
@@ -197,8 +197,8 @@ Client.prototype._removeScript = function(desc) {
Client.prototype._onResponse = function(res) {
- var cb,
- index = -1;
+ var cb;
+ var index = -1;
this._reqCallbacks.some(function(fn, i) {
if (fn.request_seq == res.body.request_seq) {
@@ -295,11 +295,11 @@ Client.prototype.reqLookup = function(refs, cb) {
};
Client.prototype.reqScopes = function(cb) {
- var self = this,
- req = {
- command: 'scopes',
- arguments: {}
- };
+ const self = this;
+ const req = {
+ command: 'scopes',
+ arguments: {}
+ };
cb = cb || function() {};
this.req(req, function(err, res) {
@@ -462,7 +462,7 @@ Client.prototype.setBreakpoint = function(req, cb) {
};
Client.prototype.clearBreakpoint = function(req, cb) {
- var req = {
+ req = {
command: 'clearbreakpoint',
arguments: req
};
@@ -525,8 +525,8 @@ Client.prototype.mirrorObject = function(handle, depth, cb) {
return;
}
- var mirror,
- waiting = 1;
+ var mirror;
+ var waiting = 1;
if (handle.className == 'Array') {
mirror = [];
@@ -676,8 +676,8 @@ var helpMessage = 'Commands: ' + commands.map(function(group) {
function SourceUnderline(sourceText, position, repl) {
if (!sourceText) return '';
- var head = sourceText.slice(0, position),
- tail = sourceText.slice(position);
+ const head = sourceText.slice(0, position);
+ var tail = sourceText.slice(position);
// Colourize char if stdout supports colours
if (repl.useColors) {
@@ -697,8 +697,8 @@ function SourceInfo(body) {
if (body.script) {
if (body.script.name) {
- var name = body.script.name,
- dir = path.resolve() + '/';
+ var name = body.script.name;
+ const dir = path.resolve() + '/';
// Change path to relative, if possible
if (name.indexOf(dir) === 0) {
@@ -969,8 +969,8 @@ Interface.prototype.controlEval = function(code, context, filename, callback) {
Interface.prototype.debugEval = function(code, context, filename, callback) {
if (!this.requireConnection()) return;
- var self = this,
- client = this.client;
+ const self = this;
+ const client = this.client;
// Repl asked for scope variables
if (code === '.scope') {
@@ -1004,9 +1004,9 @@ Interface.prototype.debugEval = function(code, context, filename, callback) {
// Adds spaces and prefix to number
// maxN is a maximum number we should have space for
function leftPad(n, prefix, maxN) {
- var s = n.toString(),
- nchars = Math.max(2, String(maxN).length) + 1,
- nspaces = nchars - s.length - 1;
+ const s = n.toString();
+ const nchars = Math.max(2, String(maxN).length) + 1;
+ const nspaces = nchars - s.length - 1;
for (var i = 0; i < nspaces; i++) {
prefix += ' ';
@@ -1078,10 +1078,10 @@ Interface.prototype.list = function(delta) {
delta || (delta = 5);
- var self = this,
- client = this.client,
- from = client.currentSourceLine - delta + 1,
- to = client.currentSourceLine + delta + 1;
+ const self = this;
+ const client = this.client;
+ const from = client.currentSourceLine - delta + 1;
+ const to = client.currentSourceLine + delta + 1;
self.pause();
client.reqSource(from, to, function(err, res) {
@@ -1096,12 +1096,12 @@ Interface.prototype.list = function(delta) {
var lineno = res.fromLine + i + 1;
if (lineno < from || lineno > to) continue;
- var current = lineno == 1 + client.currentSourceLine,
- breakpoint = client.breakpoints.some(function(bp) {
- return (bp.scriptReq === client.currentScript ||
- bp.script === client.currentScript) &&
- bp.line == lineno;
- });
+ const current = lineno == 1 + client.currentSourceLine;
+ const breakpoint = client.breakpoints.some(function(bp) {
+ return (bp.scriptReq === client.currentScript ||
+ bp.script === client.currentScript) &&
+ bp.line == lineno;
+ });
if (lineno == 1) {
// The first line needs to have the module wrapper filtered out of
@@ -1139,8 +1139,8 @@ Interface.prototype.list = function(delta) {
Interface.prototype.backtrace = function() {
if (!this.requireConnection()) return;
- var self = this,
- client = this.client;
+ const self = this;
+ const client = this.client;
self.pause();
client.fullTrace(function(err, bt) {
@@ -1153,8 +1153,8 @@ Interface.prototype.backtrace = function() {
if (bt.totalFrames == 0) {
self.print('(empty stack)');
} else {
- var trace = [],
- firstFrameNative = bt.frames[0].script.isNative;
+ const trace = [];
+ const firstFrameNative = bt.frames[0].script.isNative;
for (var i = 0; i < bt.frames.length; i++) {
var frame = bt.frames[i];
@@ -1183,9 +1183,9 @@ Interface.prototype.backtrace = function() {
Interface.prototype.scripts = function() {
if (!this.requireConnection()) return;
- var client = this.client,
- displayNatives = arguments[0] || false,
- scripts = [];
+ const client = this.client;
+ const displayNatives = arguments[0] || false;
+ const scripts = [];
this.pause();
for (var id in client.scripts) {
@@ -1323,9 +1323,9 @@ Interface.prototype.setBreakpoint = function(script, line,
condition, silent) {
if (!this.requireConnection()) return;
- var self = this,
- scriptId,
- ambiguous;
+ const self = this;
+ var scriptId;
+ var ambiguous;
// setBreakpoint() should insert breakpoint on current line
if (script === undefined) {
@@ -1345,9 +1345,10 @@ Interface.prototype.setBreakpoint = function(script, line,
return;
}
+ let req;
if (/\(\)$/.test(script)) {
// setBreakpoint('functionname()');
- var req = {
+ req = {
type: 'function',
target: script.replace(/\(\)$/, ''),
condition: condition
@@ -1373,7 +1374,6 @@ Interface.prototype.setBreakpoint = function(script, line,
if (ambiguous) return this.error('Script name is ambiguous');
if (line <= 0) return this.error('Line should be a positive value');
- var req;
if (scriptId) {
req = {
type: 'scriptId',
@@ -1429,10 +1429,10 @@ Interface.prototype.setBreakpoint = function(script, line,
Interface.prototype.clearBreakpoint = function(script, line) {
if (!this.requireConnection()) return;
- var ambiguous,
- breakpoint,
- scriptId,
- index;
+ var ambiguous;
+ var breakpoint;
+ var scriptId;
+ var index;
this.client.breakpoints.some(function(bp, i) {
if (bp.scriptId === script ||
@@ -1474,10 +1474,8 @@ Interface.prototype.clearBreakpoint = function(script, line) {
return this.error('Breakpoint not found on line ' + line);
}
- var self = this,
- req = {
- breakpoint: breakpoint
- };
+ var self = this;
+ const req = {breakpoint};
self.pause();
self.client.clearBreakpoint(req, function(err, res) {
@@ -1513,8 +1511,8 @@ Interface.prototype.breakpoints = function() {
Interface.prototype.pause_ = function() {
if (!this.requireConnection()) return;
- var self = this,
- cmd = 'process._debugPause();';
+ const self = this;
+ const cmd = 'process._debugPause();';
this.pause();
this.client.reqFrameEval(cmd, NO_FRAME, function(err, res) {
@@ -1621,18 +1619,18 @@ Interface.prototype.killChild = function() {
// Spawns child process (and restores breakpoints)
Interface.prototype.trySpawn = function(cb) {
- var self = this,
- breakpoints = this.breakpoints || [],
- port = exports.port,
- host = '127.0.0.1',
- childArgs = this.args;
+ const self = this;
+ const breakpoints = this.breakpoints || [];
+ var port = exports.port;
+ var host = '127.0.0.1';
+ var childArgs = this.args;
this.killChild();
assert(!this.child);
var isRemote = false;
if (this.args.length === 2) {
- var match = this.args[1].match(/^([^:]+):(\d+)$/);
+ const match = this.args[1].match(/^([^:]+):(\d+)$/);
if (match) {
// Connecting to remote debugger
@@ -1656,7 +1654,7 @@ Interface.prototype.trySpawn = function(cb) {
}
isRemote = true;
} else {
- var match = this.args[1].match(/^--port=(\d+)$/);
+ const match = this.args[1].match(/^--port=(\d+)$/);
if (match) {
// Start debugger on custom port
// `node debug --port=5858 app.js`
@@ -1676,8 +1674,8 @@ Interface.prototype.trySpawn = function(cb) {
this.pause();
- var client = self.client = new Client(),
- connectionAttempts = 0;
+ const client = self.client = new Client();
+ var connectionAttempts = 0;
client.once('ready', function() {
self.stdout.write(' ok\n');
diff --git a/lib/_http_client.js b/lib/_http_client.js
index db1db7bcc3ab60..a5cccbdef80f8b 100644
--- a/lib/_http_client.js
+++ b/lib/_http_client.js
@@ -115,8 +115,7 @@ function ClientRequest(options, cb) {
if (self.socketPath) {
self._last = true;
self.shouldKeepAlive = false;
- var conn = self.agent.createConnection({ path: self.socketPath });
- self.onSocket(conn);
+ self.onSocket(self.agent.createConnection({ path: self.socketPath }));
} else if (self.agent) {
// If there is an agent we should default to Connection:keep-alive,
// but only if the Agent will actually reuse the connection!
@@ -135,12 +134,11 @@ function ClientRequest(options, cb) {
self._last = true;
self.shouldKeepAlive = false;
if (options.createConnection) {
- var conn = options.createConnection(options);
+ self.onSocket(options.createConnection(options));
} else {
debug('CLIENT use net.createConnection', options);
- var conn = net.createConnection(options);
+ self.onSocket(net.createConnection(options));
}
- self.onSocket(conn);
}
self._deferToConnect(null, null, function() {
diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js
index e16f198dba71bd..4f001041f8af89 100644
--- a/lib/_http_incoming.js
+++ b/lib/_http_incoming.js
@@ -159,7 +159,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) {
default:
// make comma-separated list
- if (dest[field] !== undefined) {
+ if (typeof dest[field] === 'string') {
dest[field] += ', ' + value;
} else {
dest[field] = value;
diff --git a/lib/_http_server.js b/lib/_http_server.js
index e2221b759bd0c4..7473008a1e8c31 100644
--- a/lib/_http_server.js
+++ b/lib/_http_server.js
@@ -64,7 +64,7 @@ const STATUS_CODES = exports.STATUS_CODES = {
426 : 'Upgrade Required', // RFC 2817
428 : 'Precondition Required', // RFC 6585
429 : 'Too Many Requests', // RFC 6585
- 431 : 'Request Header Fields Too Large',// RFC 6585
+ 431 : 'Request Header Fields Too Large', // RFC 6585
500 : 'Internal Server Error',
501 : 'Not Implemented',
502 : 'Bad Gateway',
diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js
index 8ff428e11ffed0..eec442226252af 100644
--- a/lib/_stream_transform.js
+++ b/lib/_stream_transform.js
@@ -75,8 +75,7 @@ function afterTransform(stream, er, data) {
if (data !== null && data !== undefined)
stream.push(data);
- if (cb)
- cb(er);
+ cb(er);
var rs = stream._readableState;
rs.reading = false;
diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js
index 1d700c9218f538..3471ccb2d03b58 100644
--- a/lib/_tls_legacy.js
+++ b/lib/_tls_legacy.js
@@ -224,9 +224,9 @@ CryptoStream.prototype._write = function write(data, encoding, cb) {
CryptoStream.prototype._writePending = function writePending() {
- var data = this._pending,
- encoding = this._pendingEncoding,
- cb = this._pendingCallback;
+ const data = this._pending;
+ const encoding = this._pendingEncoding;
+ const cb = this._pendingCallback;
this._pending = null;
this._pendingEncoding = '';
@@ -252,9 +252,9 @@ CryptoStream.prototype._read = function read(size) {
out = this.pair.ssl.encOut;
}
- var bytesRead = 0,
- start = this._buffer.offset,
- last = start;
+ var bytesRead = 0;
+ const start = this._buffer.offset;
+ var last = start;
do {
assert(last === this._buffer.offset);
var read = this._buffer.use(this.pair.ssl, out, size - bytesRead);
@@ -604,8 +604,8 @@ function onhandshakedone() {
function onclienthello(hello) {
- var self = this,
- once = false;
+ const self = this;
+ var once = false;
this._resumingSession = true;
function callback(err, session) {
@@ -614,13 +614,15 @@ function onclienthello(hello) {
if (err) return self.socket.destroy(err);
- self.ssl.loadSession(session);
- self.ssl.endParser();
+ setImmediate(function() {
+ self.ssl.loadSession(session);
+ self.ssl.endParser();
- // Cycle data
- self._resumingSession = false;
- self.cleartext.read(0);
- self.encrypted.read(0);
+ // Cycle data
+ self._resumingSession = false;
+ self.cleartext.read(0);
+ self.encrypted.read(0);
+ });
}
if (hello.sessionId.length <= 0 ||
diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js
index 5b3690696ece66..35d5ba3b381fe3 100644
--- a/lib/_tls_wrap.js
+++ b/lib/_tls_wrap.js
@@ -397,8 +397,8 @@ TLSSocket.prototype._init = function(socket, wrap) {
// For clients, we will always have either a given ca list or be using
// default one
- var requestCert = !!options.requestCert || !options.isServer,
- rejectUnauthorized = !!options.rejectUnauthorized;
+ const requestCert = !!options.requestCert || !options.isServer;
+ const rejectUnauthorized = !!options.rejectUnauthorized;
this._requestCert = requestCert;
this._rejectUnauthorized = rejectUnauthorized;
@@ -494,8 +494,8 @@ TLSSocket.prototype._init = function(socket, wrap) {
};
TLSSocket.prototype.renegotiate = function(options, callback) {
- var requestCert = this._requestCert,
- rejectUnauthorized = this._rejectUnauthorized;
+ var requestCert = this._requestCert;
+ var rejectUnauthorized = this._rejectUnauthorized;
if (this.destroyed)
return;
@@ -966,9 +966,9 @@ exports.connect = function(/* [port, host], options, cb */) {
var hostname = options.servername ||
options.host ||
(options.socket && options.socket._host) ||
- 'localhost',
- NPN = {},
- context = tls.createSecureContext(options);
+ 'localhost';
+ const NPN = {};
+ const context = tls.createSecureContext(options);
tls.convertNPNProtocols(options.NPNProtocols, NPN);
var socket = new TLSSocket(options.socket, {
diff --git a/lib/assert.js b/lib/assert.js
index 3e52ab45f66127..928420521e03e3 100644
--- a/lib/assert.js
+++ b/lib/assert.js
@@ -198,8 +198,8 @@ function objEquiv(a, b, strict) {
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
- var aIsArgs = isArguments(a),
- bIsArgs = isArguments(b);
+ const aIsArgs = isArguments(a);
+ const bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
@@ -207,9 +207,9 @@ function objEquiv(a, b, strict) {
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
- var ka = Object.keys(a),
- kb = Object.keys(b),
- key, i;
+ const ka = Object.keys(a);
+ const kb = Object.keys(b);
+ var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
diff --git a/lib/buffer.js b/lib/buffer.js
index 9c6b6c94162833..a830f2a8e39017 100644
--- a/lib/buffer.js
+++ b/lib/buffer.js
@@ -258,6 +258,9 @@ function base64ByteLength(str, bytes) {
function byteLength(string, encoding) {
+ if (string instanceof Buffer)
+ return string.length;
+
if (typeof string !== 'string')
string = '' + string;
@@ -513,9 +516,6 @@ Buffer.prototype.set = internalUtil.deprecate(function set(offset, v) {
return this[offset] = v;
}, 'Buffer.set is deprecated. Use array indexes instead.');
-
-// TODO(trevnorris): fix these checks to follow new standard
-// write(string, offset = 0, length = buffer.length, encoding = 'utf8')
var writeWarned = false;
const writeMsg = 'Buffer.write(string, encoding, offset, length) is ' +
'deprecated. Use write(string[, offset[, length]]' +
@@ -608,8 +608,6 @@ Buffer.prototype.toJSON = function() {
};
-// TODO(trevnorris): currently works like Array.prototype.slice(), which
-// doesn't follow the new standard for throwing on out of range indexes.
Buffer.prototype.slice = function slice(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
diff --git a/lib/cluster.js b/lib/cluster.js
index f202f25cdd522a..82e0e4c628342f 100644
--- a/lib/cluster.js
+++ b/lib/cluster.js
@@ -428,7 +428,7 @@ function masterInit() {
else if (message.act === 'listening')
listening(worker, message);
else if (message.act === 'suicide')
- worker.suicide = true;
+ suicide(worker, message);
else if (message.act === 'close')
close(worker, message);
}
@@ -439,7 +439,15 @@ function masterInit() {
cluster.emit('online', worker);
}
+ function suicide(worker, message) {
+ worker.suicide = true;
+ send(worker, { ack: message.seq });
+ }
+
function queryServer(worker, message) {
+ // Stop processing if worker already disconnecting
+ if (worker.suicide)
+ return;
var args = [message.address,
message.port,
message.addressType,
@@ -532,7 +540,7 @@ function workerInit() {
if (message.act === 'newconn')
onconnection(message, handle);
else if (message.act === 'disconnect')
- worker.disconnect();
+ _disconnect.call(worker, true);
}
};
@@ -653,14 +661,36 @@ function workerInit() {
}
Worker.prototype.disconnect = function() {
+ _disconnect.call(this);
+ };
+
+ Worker.prototype.destroy = function() {
+ this.suicide = true;
+ if (!this.isConnected()) process.exit(0);
+ var exit = process.exit.bind(null, 0);
+ send({ act: 'suicide' }, () => process.disconnect());
+ process.once('disconnect', exit);
+ };
+
+ function send(message, cb) {
+ sendHelper(process, message, null, cb);
+ }
+
+ function _disconnect(masterInitiated) {
this.suicide = true;
let waitingCount = 1;
function checkWaitingCount() {
waitingCount--;
if (waitingCount === 0) {
- send({ act: 'suicide' });
- process.disconnect();
+ // If disconnect is worker initiated, wait for ack to be sure suicide
+ // is properly set in the master, otherwise, if it's master initiated
+ // there's no need to send the suicide message
+ if (masterInitiated) {
+ process.disconnect();
+ } else {
+ send({ act: 'suicide' }, () => process.disconnect());
+ }
}
}
@@ -672,19 +702,6 @@ function workerInit() {
}
checkWaitingCount();
- };
-
- Worker.prototype.destroy = function() {
- this.suicide = true;
- if (!this.isConnected()) process.exit(0);
- var exit = process.exit.bind(null, 0);
- send({ act: 'suicide' }, exit);
- process.once('disconnect', exit);
- process.disconnect();
- };
-
- function send(message, cb) {
- sendHelper(process, message, null, cb);
}
}
diff --git a/lib/dgram.js b/lib/dgram.js
index 161f908eae547e..da1308d7074222 100644
--- a/lib/dgram.js
+++ b/lib/dgram.js
@@ -134,8 +134,9 @@ function replaceHandle(self, newHandle) {
self._handle = newHandle;
}
-Socket.prototype.bind = function(port /*, address, callback*/) {
+Socket.prototype.bind = function(port_ /*, address, callback*/) {
var self = this;
+ let port = port_;
self._healthCheck();
diff --git a/lib/fs.js b/lib/fs.js
index 57e9220a149f28..81f8a3c3ddc1a7 100644
--- a/lib/fs.js
+++ b/lib/fs.js
@@ -552,8 +552,8 @@ fs.openSync = function(path, flags, mode) {
fs.read = function(fd, buffer, offset, length, position, callback) {
if (!(buffer instanceof Buffer)) {
// legacy string interface (fd, length, position, encoding, callback)
- var cb = arguments[4],
- encoding = arguments[3];
+ const cb = arguments[4];
+ const encoding = arguments[3];
assertEncoding(encoding);
@@ -1388,9 +1388,9 @@ fs.realpathSync = function realpathSync(p, cache) {
return cache[p];
}
- var original = p,
- seenLinks = {},
- knownHard = {};
+ const original = p;
+ const seenLinks = {};
+ const knownHard = {};
// current character position in p
var pos;
@@ -1490,9 +1490,9 @@ fs.realpath = function realpath(p, cache, cb) {
return process.nextTick(cb.bind(null, null, cache[p]));
}
- var original = p,
- seenLinks = {},
- knownHard = {};
+ const original = p;
+ const seenLinks = {};
+ const knownHard = {};
// current character position in p
var pos;
@@ -1941,9 +1941,9 @@ util.inherits(SyncWriteStream, Stream);
// Export
Object.defineProperty(fs, 'SyncWriteStream', {
- configurable: true,
- writable: true,
- value: SyncWriteStream
+ configurable: true,
+ writable: true,
+ value: SyncWriteStream
});
SyncWriteStream.prototype.write = function(data, arg1, arg2) {
diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js
index b4365fb8c067f7..ce4cd6496fd1d2 100644
--- a/lib/internal/child_process.js
+++ b/lib/internal/child_process.js
@@ -250,11 +250,11 @@ function getHandleWrapType(stream) {
ChildProcess.prototype.spawn = function(options) {
- var self = this,
- ipc,
- ipcFd,
- // If no `stdio` option was given - use default
- stdio = options.stdio || 'pipe';
+ const self = this;
+ var ipc;
+ var ipcFd;
+ // If no `stdio` option was given - use default
+ var stdio = options.stdio || 'pipe';
stdio = _validateStdio(stdio, false);
@@ -692,8 +692,8 @@ function handleMessage(target, message, handle) {
function nop() { }
function _validateStdio(stdio, sync) {
- var ipc,
- ipcFd;
+ var ipc;
+ var ipcFd;
// Replace shortcut with an array
if (typeof stdio === 'string') {
diff --git a/lib/internal/repl.js b/lib/internal/repl.js
index e6b41fbdd89b65..371446a83bd4fd 100644
--- a/lib/internal/repl.js
+++ b/lib/internal/repl.js
@@ -55,15 +55,26 @@ function createRepl(env, opts, cb) {
}
const repl = REPL.start(opts);
- if (opts.terminal && env.NODE_REPL_HISTORY !== '') {
+ if (opts.terminal) {
return setupHistory(repl, env.NODE_REPL_HISTORY,
env.NODE_REPL_HISTORY_FILE, cb);
}
+
repl._historyPrev = _replHistoryMessage;
cb(null, repl);
}
function setupHistory(repl, historyPath, oldHistoryPath, ready) {
+ // Empty string disables persistent history.
+
+ if (typeof historyPath === 'string')
+ historyPath = historyPath.trim();
+
+ if (historyPath === '') {
+ repl._historyPrev = _replHistoryMessage;
+ return ready(null, repl);
+ }
+
if (!historyPath) {
try {
historyPath = path.join(os.homedir(), '.node_repl_history');
diff --git a/lib/module.js b/lib/module.js
index 1d937f8baa2aa8..7e3a1a09174752 100644
--- a/lib/module.js
+++ b/lib/module.js
@@ -126,19 +126,18 @@ function tryExtensions(p, exts) {
var warned = false;
Module._findPath = function(request, paths) {
- var exts = Object.keys(Module._extensions);
-
if (path.isAbsolute(request)) {
paths = [''];
}
- var trailingSlash = (request.slice(-1) === '/');
-
var cacheKey = JSON.stringify({request: request, paths: paths});
if (Module._pathCache[cacheKey]) {
return Module._pathCache[cacheKey];
}
+ const exts = Object.keys(Module._extensions);
+ const trailingSlash = request.slice(-1) === '/';
+
// For each path
for (var i = 0, PL = paths.length; i < PL; i++) {
// Don't search further if path doesn't exist
diff --git a/lib/net.js b/lib/net.js
index f778043572362e..21f1f8e0c6e465 100644
--- a/lib/net.js
+++ b/lib/net.js
@@ -722,10 +722,10 @@ function createWriteReq(req, handle, data, encoding) {
Socket.prototype.__defineGetter__('bytesWritten', function() {
- var bytes = this._bytesDispatched,
- state = this._writableState,
- data = this._pendingData,
- encoding = this._pendingEncoding;
+ var bytes = this._bytesDispatched;
+ const state = this._writableState;
+ const data = this._pendingData;
+ const encoding = this._pendingEncoding;
if (!state)
return undefined;
@@ -931,7 +931,6 @@ function lookupAndConnect(self, options) {
port |= 0;
// If host is an IP, skip performing a lookup
- // TODO(evanlucas) should we hot path this for localhost?
var addressType = exports.isIP(host);
if (addressType) {
process.nextTick(function() {
@@ -951,12 +950,12 @@ function lookupAndConnect(self, options) {
if (dnsopts.family !== 4 && dnsopts.family !== 6) {
dnsopts.hints = dns.ADDRCONFIG;
- // The AI_V4MAPPED hint is not supported on FreeBSD, and getaddrinfo
- // returns EAI_BADFLAGS. However, it seems to be supported on most other
- // systems. See
+ // The AI_V4MAPPED hint is not supported on FreeBSD or Android,
+ // and getaddrinfo returns EAI_BADFLAGS. However, it seems to be
+ // supported on most other systems. See
// http://lists.freebsd.org/pipermail/freebsd-bugs/2008-February/028260.html
// for more information on the lack of support for FreeBSD.
- if (process.platform !== 'freebsd')
+ if (process.platform !== 'freebsd' && process.platform !== 'android')
dnsopts.hints |= dns.V4MAPPED;
}
@@ -1132,8 +1131,7 @@ function _listen(handle, backlog) {
return handle.listen(backlog || 511);
}
-var createServerHandle = exports._createServerHandle =
- function(address, port, addressType, fd) {
+function createServerHandle(address, port, addressType, fd) {
var err = 0;
// assign handle in listen, and clean up if bind or listen fails
var handle;
@@ -1189,6 +1187,7 @@ var createServerHandle = exports._createServerHandle =
return handle;
};
+exports._createServerHandle = createServerHandle;
Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
@@ -1444,8 +1443,8 @@ Server.prototype.getConnections = function(cb) {
}
// Poll slaves
- var left = this._slaves.length,
- total = this._connections;
+ var left = this._slaves.length;
+ var total = this._connections;
function oncount(err, count) {
if (err) {
@@ -1487,8 +1486,8 @@ Server.prototype.close = function(cb) {
}
if (this._usingSlaves) {
- var self = this,
- left = this._slaves.length;
+ var self = this;
+ var left = this._slaves.length;
// Increment connections to be sure that, even if all sockets will be closed
// during polling of slaves, `close` event will be emitted only once.
diff --git a/lib/path.js b/lib/path.js
index 0c9c656e66c3a7..c867dac83b9aad 100644
--- a/lib/path.js
+++ b/lib/path.js
@@ -74,21 +74,21 @@ var win32 = {};
// Function to split a filename into [root, dir, basename, ext]
function win32SplitPath(filename) {
// Separate device+slash from tail
- var result = splitDeviceRe.exec(filename),
- device = (result[1] || '') + (result[2] || ''),
- tail = result[3];
+ const result = splitDeviceRe.exec(filename);
+ const device = (result[1] || '') + (result[2] || '');
+ const tail = result[3];
// Split the tail into dir, basename and extension
- var result2 = splitTailRe.exec(tail),
- dir = result2[1],
- basename = result2[2],
- ext = result2[3];
+ const result2 = splitTailRe.exec(tail);
+ const dir = result2[1];
+ const basename = result2[2];
+ const ext = result2[3];
return [device, dir, basename, ext];
}
function win32StatPath(path) {
- var result = splitDeviceRe.exec(path),
- device = result[1] || '',
- isUnc = !!device && device[1] !== ':';
+ const result = splitDeviceRe.exec(path);
+ const device = result[1] || '';
+ const isUnc = !!device && device[1] !== ':';
return {
device,
isUnc,
@@ -103,9 +103,9 @@ function normalizeUNCRoot(device) {
// path.resolve([from ...], to)
win32.resolve = function() {
- var resolvedDevice = '',
- resolvedTail = '',
- resolvedAbsolute = false;
+ var resolvedDevice = '';
+ var resolvedTail = '';
+ var resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1; i--) {
var path;
@@ -134,11 +134,11 @@ win32.resolve = function() {
continue;
}
- var result = win32StatPath(path),
- device = result.device,
- isUnc = result.isUnc,
- isAbsolute = result.isAbsolute,
- tail = result.tail;
+ const result = win32StatPath(path);
+ const device = result.device;
+ var isUnc = result.isUnc;
+ const isAbsolute = result.isAbsolute;
+ const tail = result.tail;
if (device &&
resolvedDevice &&
@@ -182,12 +182,12 @@ win32.resolve = function() {
win32.normalize = function(path) {
assertPath(path);
- var result = win32StatPath(path),
- device = result.device,
- isUnc = result.isUnc,
- isAbsolute = result.isAbsolute,
- tail = result.tail,
- trailingSlash = /[\\\/]$/.test(tail);
+ const result = win32StatPath(path);
+ var device = result.device;
+ const isUnc = result.isUnc;
+ const isAbsolute = result.isAbsolute;
+ var tail = result.tail;
+ const trailingSlash = /[\\\/]$/.test(tail);
// Normalize the tail path
tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\');
@@ -318,9 +318,9 @@ win32._makeLong = function(path) {
win32.dirname = function(path) {
- var result = win32SplitPath(path),
- root = result[0],
- dir = result[1];
+ const result = win32SplitPath(path);
+ const root = result[0];
+ var dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
@@ -417,8 +417,8 @@ function posixSplitPath(filename) {
// path.resolve([from ...], to)
// posix version
posix.resolve = function() {
- var resolvedPath = '',
- resolvedAbsolute = false;
+ var resolvedPath = '';
+ var resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
@@ -449,8 +449,8 @@ posix.resolve = function() {
posix.normalize = function(path) {
assertPath(path);
- var isAbsolute = posix.isAbsolute(path),
- trailingSlash = path && path[path.length - 1] === '/';
+ const isAbsolute = posix.isAbsolute(path);
+ const trailingSlash = path && path[path.length - 1] === '/';
// Normalize the path
path = normalizeArray(path.split('/'), !isAbsolute).join('/');
@@ -527,9 +527,9 @@ posix._makeLong = function(path) {
posix.dirname = function(path) {
- var result = posixSplitPath(path),
- root = result[0],
- dir = result[1];
+ const result = posixSplitPath(path);
+ const root = result[0];
+ var dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
diff --git a/lib/querystring.js b/lib/querystring.js
index 40677ffb0f0859..5f8df93038921f 100644
--- a/lib/querystring.js
+++ b/lib/querystring.js
@@ -230,9 +230,9 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
var keys = [];
for (var i = 0; i < len; ++i) {
- var x = qs[i].replace(regexp, '%20'),
- idx = x.indexOf(eq),
- k, v;
+ const x = qs[i].replace(regexp, '%20');
+ const idx = x.indexOf(eq);
+ var k, v;
if (idx >= 0) {
k = decodeStr(x.substring(0, idx), decode);
diff --git a/lib/readline.js b/lib/readline.js
index 0f9aabb2fec475..8ee10850e54f89 100644
--- a/lib/readline.js
+++ b/lib/readline.js
@@ -9,6 +9,7 @@
const kHistorySize = 30;
const util = require('util');
+const debug = util.debuglog('readline');
const internalUtil = require('internal/util');
const inherits = util.inherits;
const Buffer = require('buffer').Buffer;
@@ -375,12 +376,12 @@ Interface.prototype._tabComplete = function() {
self.resume();
if (err) {
- // XXX Log it somewhere?
+ debug('tab completion error %j', err);
return;
}
- var completions = rv[0],
- completeOn = rv[1]; // the text that was completed
+ const completions = rv[0];
+ const completeOn = rv[1]; // the text that was completed
if (completions && completions.length) {
// Apply/show completions.
if (completions.length === 1) {
diff --git a/lib/tls.js b/lib/tls.js
index 8bd9991d8746b2..aad17c9ef2d6a3 100644
--- a/lib/tls.js
+++ b/lib/tls.js
@@ -90,12 +90,12 @@ exports.checkServerIdentity = function checkServerIdentity(host, cert) {
return new RegExp('^' + re + '$', 'i');
}
- var dnsNames = [],
- uriNames = [],
- ips = [],
- matchCN = true,
- valid = false,
- reason = 'Unknown reason';
+ var dnsNames = [];
+ var uriNames = [];
+ const ips = [];
+ var matchCN = true;
+ var valid = false;
+ var reason = 'Unknown reason';
// There're several names to perform check against:
// CN and altnames in certificate extension
diff --git a/lib/url.js b/lib/url.js
index 6489d6327d0e29..7348eadb7a9c6e 100644
--- a/lib/url.js
+++ b/lib/url.js
@@ -93,11 +93,11 @@ Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
- var queryIndex = url.indexOf('?'),
- splitter =
- (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
- uSplit = url.split(splitter),
- slashRegex = /\\/g;
+ const queryIndex = url.indexOf('?');
+ const splitter =
+ (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#';
+ const uSplit = url.split(splitter);
+ const slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
@@ -370,11 +370,11 @@ Url.prototype.format = function() {
auth += '@';
}
- var protocol = this.protocol || '',
- pathname = this.pathname || '',
- hash = this.hash || '',
- host = false,
- query = '';
+ var protocol = this.protocol || '';
+ var pathname = this.pathname || '';
+ var hash = this.hash || '';
+ var host = false;
+ var query = '';
if (this.host) {
host = auth + this.host;
@@ -525,17 +525,17 @@ Url.prototype.resolveObject = function(relative) {
return result;
}
- var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
- isRelAbs = (
- relative.host ||
- relative.pathname && relative.pathname.charAt(0) === '/'
- ),
- mustEndAbs = (isRelAbs || isSourceAbs ||
- (result.host && relative.pathname)),
- removeAllDots = mustEndAbs,
- srcPath = result.pathname && result.pathname.split('/') || [],
- relPath = relative.pathname && relative.pathname.split('/') || [],
- psychotic = result.protocol && !slashedProtocol[result.protocol];
+ const isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/');
+ const isRelAbs = (
+ relative.host ||
+ relative.pathname && relative.pathname.charAt(0) === '/'
+ );
+ var mustEndAbs = (isRelAbs || isSourceAbs ||
+ (result.host && relative.pathname));
+ const removeAllDots = mustEndAbs;
+ var srcPath = result.pathname && result.pathname.split('/') || [];
+ var relPath = relative.pathname && relative.pathname.split('/') || [];
+ const psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
diff --git a/src/debug-agent.cc b/src/debug-agent.cc
index 3409fb2603ae9b..06ede7fdef4aa9 100644
--- a/src/debug-agent.cc
+++ b/src/debug-agent.cc
@@ -321,6 +321,8 @@ void Agent::EnqueueMessage(AgentMessage* message) {
void Agent::MessageHandler(const v8::Debug::Message& message) {
Isolate* isolate = message.GetIsolate();
Environment* env = Environment::GetCurrent(isolate);
+ if (env == nullptr)
+ return; // Called from a non-node context.
Agent* a = env->debugger_agent();
CHECK_NE(a, nullptr);
CHECK_EQ(isolate, a->parent_env()->isolate());
diff --git a/src/node.js b/src/node.js
index b38594f7c09274..c194c239ca5866 100644
--- a/src/node.js
+++ b/src/node.js
@@ -61,13 +61,11 @@
} else if (process.argv[1] == 'debug') {
// Start the debugger agent
- var d = NativeModule.require('_debugger');
- d.start();
+ NativeModule.require('_debugger').start();
} else if (process.argv[1] == '--debug-agent') {
// Start the debugger agent
- var d = NativeModule.require('_debug_agent');
- d.start();
+ NativeModule.require('_debug_agent').start();
} else {
// There is user code to be run
@@ -137,8 +135,6 @@
}
} else {
- var Module = NativeModule.require('module');
-
// If -i or --interactive were passed, or stdin is a TTY.
if (process._forceRepl || NativeModule.require('tty').isatty(0)) {
// REPL
@@ -555,7 +551,7 @@
// getcwd(3) can fail if the current working directory has been deleted.
// Fall back to the directory name of the (absolute) executable path.
// It's not really correct but what are the alternatives?
- var cwd = path.dirname(process.execPath);
+ cwd = path.dirname(process.execPath);
}
var module = new Module(name);
diff --git a/src/node_contextify.cc b/src/node_contextify.cc
index bfd45a22862a06..59a90c88c9993f 100644
--- a/src/node_contextify.cc
+++ b/src/node_contextify.cc
@@ -239,37 +239,26 @@ class ContextifyContext {
static void RunInDebugContext(const FunctionCallbackInfo& args) {
- // Ensure that the debug context has an Environment assigned in case
- // a fatal error is raised. The fatal exception handler in node.cc
- // is not equipped to deal with contexts that don't have one and
- // can't easily be taught that due to a deficiency in the V8 API:
- // there is no way for the embedder to tell if the data index is
- // in use.
- struct ScopedEnvironment {
- ScopedEnvironment(Local context, Environment* env)
- : context_(context) {
- const int index = Environment::kContextEmbedderDataIndex;
- context->SetAlignedPointerInEmbedderData(index, env);
- }
- ~ScopedEnvironment() {
- const int index = Environment::kContextEmbedderDataIndex;
- context_->SetAlignedPointerInEmbedderData(index, nullptr);
- }
- Local context_;
- };
-
Local script_source(args[0]->ToString(args.GetIsolate()));
if (script_source.IsEmpty())
return; // Exception pending.
Local debug_context = Debug::GetDebugContext();
+ Environment* env = Environment::GetCurrent(args);
if (debug_context.IsEmpty()) {
// Force-load the debug context.
Debug::GetMirror(args.GetIsolate()->GetCurrentContext(), args[0]);
debug_context = Debug::GetDebugContext();
CHECK(!debug_context.IsEmpty());
+ // Ensure that the debug context has an Environment assigned in case
+ // a fatal error is raised. The fatal exception handler in node.cc
+ // is not equipped to deal with contexts that don't have one and
+ // can't easily be taught that due to a deficiency in the V8 API:
+ // there is no way for the embedder to tell if the data index is
+ // in use.
+ const int index = Environment::kContextEmbedderDataIndex;
+ debug_context->SetAlignedPointerInEmbedderData(index, env);
}
- Environment* env = Environment::GetCurrent(args);
- ScopedEnvironment env_scope(debug_context, env);
+
Context::Scope context_scope(debug_context);
Local
+
+