Browse Source

lib: reduce util.is*() usage

Many of the util.is*() methods used to check data types
simply compare against a single value or the result of
typeof. This commit replaces calls to these methods with
equivalent checks. This commit does not touch calls to the
more complex methods (isRegExp(), isDate(), etc.).

Fixes: https://github.com/iojs/io.js/issues/607
PR-URL: https://github.com/iojs/io.js/pull/647
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
v1.8.0-commit
cjihrig 10 years ago
parent
commit
6ac8bdc0ab
  1. 24
      lib/_debugger.js
  2. 13
      lib/_http_client.js
  3. 3
      lib/_http_common.js
  4. 6
      lib/_http_incoming.js
  5. 27
      lib/_http_outgoing.js
  6. 6
      lib/_http_server.js
  7. 20
      lib/_stream_readable.js
  8. 6
      lib/_stream_transform.js
  9. 25
      lib/_stream_writable.js
  10. 7
      lib/_tls_common.js
  11. 14
      lib/_tls_legacy.js
  12. 21
      lib/_tls_wrap.js
  13. 14
      lib/assert.js
  14. 40
      lib/buffer.js
  15. 55
      lib/child_process.js
  16. 22
      lib/cluster.js
  17. 2
      lib/console.js
  18. 16
      lib/crypto.js
  19. 24
      lib/dgram.js
  20. 14
      lib/dns.js
  21. 35
      lib/events.js
  22. 142
      lib/fs.js
  23. 16
      lib/https.js
  24. 2
      lib/module.js
  25. 66
      lib/net.js
  26. 24
      lib/path.js
  27. 20
      lib/querystring.js
  28. 45
      lib/readline.js
  29. 24
      lib/repl.js
  30. 8
      lib/smalloc.js
  31. 2
      lib/stream.js
  32. 8
      lib/tls.js
  33. 5
      lib/tty.js
  34. 19
      lib/url.js
  35. 88
      lib/util.js
  36. 3
      lib/vm.js
  37. 30
      lib/zlib.js

24
lib/_debugger.js

@ -164,7 +164,8 @@ exports.Client = Client;
Client.prototype._addHandle = function(desc) { Client.prototype._addHandle = function(desc) {
if (!util.isObject(desc) || !util.isNumber(desc.handle)) { if (desc === null || typeof desc !== 'object' ||
typeof desc.handle !== 'number') {
return; return;
} }
@ -282,7 +283,7 @@ Client.prototype.reqLookup = function(refs, cb) {
this.req(req, function(err, res) { this.req(req, function(err, res) {
if (err) return cb(err); if (err) return cb(err);
for (var ref in res) { for (var ref in res) {
if (util.isObject(res[ref])) { if (res[ref] !== null && typeof res[ref] === 'object') {
self._addHandle(res[ref]); self._addHandle(res[ref]);
} }
} }
@ -544,8 +545,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) {
mirrorValue = '[?]'; mirrorValue = '[?]';
} }
if (Array.isArray(mirror) && typeof prop.name !== 'number') {
if (util.isArray(mirror) && !util.isNumber(prop.name)) {
// Skip the 'length' property. // Skip the 'length' property.
return; return;
} }
@ -578,7 +578,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) {
val = function() {}; val = function() {};
} else if (handle.type === 'null') { } else if (handle.type === 'null') {
val = null; val = null;
} else if (!util.isUndefined(handle.value)) { } else if (handle.value !== undefined) {
val = handle.value; val = handle.value;
} else if (handle.type === 'undefined') { } else if (handle.type === 'undefined') {
val = undefined; val = undefined;
@ -879,7 +879,7 @@ Interface.prototype.print = function(text, oneline) {
if (this.killed) return; if (this.killed) return;
this.clearline(); this.clearline();
this.stdout.write(util.isString(text) ? text : util.inspect(text)); this.stdout.write(typeof text === 'string' ? text : util.inspect(text));
if (oneline !== true) { if (oneline !== true) {
this.stdout.write('\n'); this.stdout.write('\n');
@ -1194,7 +1194,7 @@ Interface.prototype.scripts = function() {
this.pause(); this.pause();
for (var id in client.scripts) { for (var id in client.scripts) {
var script = client.scripts[id]; var script = client.scripts[id];
if (util.isObject(script) && script.name) { if (script !== null && typeof script === 'object' && script.name) {
if (displayNatives || if (displayNatives ||
script.name == client.currentScript || script.name == client.currentScript ||
!script.isNative) { !script.isNative) {
@ -1332,13 +1332,13 @@ Interface.prototype.setBreakpoint = function(script, line,
ambiguous; ambiguous;
// setBreakpoint() should insert breakpoint on current line // setBreakpoint() should insert breakpoint on current line
if (util.isUndefined(script)) { if (script === undefined) {
script = this.client.currentScript; script = this.client.currentScript;
line = this.client.currentSourceLine + 1; line = this.client.currentSourceLine + 1;
} }
// setBreakpoint(line-number) should insert breakpoint in current script // setBreakpoint(line-number) should insert breakpoint in current script
if (util.isUndefined(line) && util.isNumber(script)) { if (line === undefined && typeof script === 'number') {
line = script; line = script;
script = this.client.currentScript; script = this.client.currentScript;
} }
@ -1442,7 +1442,7 @@ Interface.prototype.clearBreakpoint = function(script, line) {
if (bp.scriptId === script || if (bp.scriptId === script ||
bp.scriptReq === script || bp.scriptReq === script ||
(bp.script && bp.script.indexOf(script) !== -1)) { (bp.script && bp.script.indexOf(script) !== -1)) {
if (!util.isUndefined(index)) { if (index !== undefined) {
ambiguous = true; ambiguous = true;
} }
scriptId = script; scriptId = script;
@ -1470,11 +1470,11 @@ Interface.prototype.clearBreakpoint = function(script, line) {
if (ambiguous) return this.error('Script name is ambiguous'); if (ambiguous) return this.error('Script name is ambiguous');
if (util.isUndefined(scriptId)) { if (scriptId === undefined) {
return this.error('Script ' + script + ' not found'); return this.error('Script ' + script + ' not found');
} }
if (util.isUndefined(breakpoint)) { if (breakpoint === undefined) {
return this.error('Breakpoint not found on line ' + line); return this.error('Breakpoint not found on line ' + line);
} }

13
lib/_http_client.js

@ -19,7 +19,7 @@ function ClientRequest(options, cb) {
var self = this; var self = this;
OutgoingMessage.call(self); OutgoingMessage.call(self);
if (util.isString(options)) { if (typeof options === 'string') {
options = url.parse(options); options = url.parse(options);
} }
@ -27,7 +27,8 @@ function ClientRequest(options, cb) {
var defaultAgent = options._defaultAgent || Agent.globalAgent; var defaultAgent = options._defaultAgent || Agent.globalAgent;
if (agent === false) { if (agent === false) {
agent = new defaultAgent.constructor(); agent = new defaultAgent.constructor();
} else if (util.isNullOrUndefined(agent) && !options.createConnection) { } else if ((agent === null || agent === undefined) &&
!options.createConnection) {
agent = defaultAgent; agent = defaultAgent;
} }
self.agent = agent; self.agent = agent;
@ -56,7 +57,7 @@ function ClientRequest(options, cb) {
var port = options.port = options.port || defaultPort || 80; var port = options.port = options.port || defaultPort || 80;
var host = options.host = options.hostname || options.host || 'localhost'; var host = options.host = options.hostname || options.host || 'localhost';
if (util.isUndefined(options.setHost)) { if (options.setHost === undefined) {
var setHost = true; var setHost = true;
} }
@ -68,7 +69,7 @@ function ClientRequest(options, cb) {
self.once('response', cb); self.once('response', cb);
} }
if (!util.isArray(options.headers)) { if (!Array.isArray(options.headers)) {
if (options.headers) { if (options.headers) {
var keys = Object.keys(options.headers); var keys = Object.keys(options.headers);
for (var i = 0, l = keys.length; i < l; i++) { for (var i = 0, l = keys.length; i < l; i++) {
@ -101,7 +102,7 @@ function ClientRequest(options, cb) {
self.useChunkedEncodingByDefault = true; self.useChunkedEncodingByDefault = true;
} }
if (util.isArray(options.headers)) { if (Array.isArray(options.headers)) {
self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
options.headers); options.headers);
} else if (self.getHeader('expect')) { } else if (self.getHeader('expect')) {
@ -446,7 +447,7 @@ function tickOnSocket(req, socket) {
httpSocketSetup(socket); httpSocketSetup(socket);
// Propagate headers limit from request object to parser // Propagate headers limit from request object to parser
if (util.isNumber(req.maxHeadersCount)) { if (typeof req.maxHeadersCount === 'number') {
parser.maxHeaderPairs = req.maxHeadersCount << 1; parser.maxHeaderPairs = req.maxHeadersCount << 1;
} else { } else {
// Set default value because parser may be reused from FreeList // Set default value because parser may be reused from FreeList

3
lib/_http_common.js

@ -8,7 +8,6 @@ const IncomingMessage = incoming.IncomingMessage;
const readStart = incoming.readStart; const readStart = incoming.readStart;
const readStop = incoming.readStop; const readStop = incoming.readStop;
const isNumber = require('util').isNumber;
const debug = require('util').debuglog('http'); const debug = require('util').debuglog('http');
exports.debug = debug; exports.debug = debug;
@ -69,7 +68,7 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method,
parser.incoming._addHeaderLines(headers, n); parser.incoming._addHeaderLines(headers, n);
if (isNumber(method)) { if (typeof method === 'number') {
// server only // server only
parser.incoming.method = HTTPParser.methods[method]; parser.incoming.method = HTTPParser.methods[method];
} else { } else {

6
lib/_http_incoming.js

@ -130,7 +130,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) {
switch (field) { switch (field) {
// Array headers: // Array headers:
case 'set-cookie': case 'set-cookie':
if (!util.isUndefined(dest[field])) { if (dest[field] !== undefined) {
dest[field].push(value); dest[field].push(value);
} else { } else {
dest[field] = [value]; dest[field] = [value];
@ -152,13 +152,13 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) {
case 'location': case 'location':
case 'max-forwards': case 'max-forwards':
// drop duplicates // drop duplicates
if (util.isUndefined(dest[field])) if (dest[field] === undefined)
dest[field] = value; dest[field] = value;
break; break;
default: default:
// make comma-separated list // make comma-separated list
if (!util.isUndefined(dest[field])) if (dest[field] !== undefined)
dest[field] += ', ' + value; dest[field] += ', ' + value;
else { else {
dest[field] = value; dest[field] = value;

27
lib/_http_outgoing.js

@ -106,7 +106,7 @@ OutgoingMessage.prototype._send = function(data, encoding, callback) {
// the same packet. Future versions of Node are going to take care of // the same packet. Future versions of Node are going to take care of
// this at a lower level and in a more general way. // this at a lower level and in a more general way.
if (!this._headerSent) { if (!this._headerSent) {
if (util.isString(data) && if (typeof data === 'string' &&
encoding !== 'hex' && encoding !== 'hex' &&
encoding !== 'base64') { encoding !== 'base64') {
data = this._header + data; data = this._header + data;
@ -122,13 +122,13 @@ OutgoingMessage.prototype._send = function(data, encoding, callback) {
OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) { OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) {
if (util.isFunction(encoding)) { if (typeof encoding === 'function') {
callback = encoding; callback = encoding;
encoding = null; encoding = null;
} }
if (data.length === 0) { if (data.length === 0) {
if (util.isFunction(callback)) if (typeof callback === 'function')
process.nextTick(callback); process.nextTick(callback);
return true; return true;
} }
@ -187,7 +187,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
if (headers) { if (headers) {
var keys = Object.keys(headers); var keys = Object.keys(headers);
var isArray = util.isArray(headers); var isArray = Array.isArray(headers);
var field, value; var field, value;
for (var i = 0, l = keys.length; i < l; i++) { for (var i = 0, l = keys.length; i < l; i++) {
@ -200,7 +200,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
value = headers[key]; value = headers[key];
} }
if (util.isArray(value)) { if (Array.isArray(value)) {
for (var j = 0; j < value.length; j++) { for (var j = 0; j < value.length; j++) {
storeHeader(this, state, field, value[j]); storeHeader(this, state, field, value[j]);
} }
@ -408,7 +408,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
return true; return true;
} }
if (!util.isString(chunk) && !util.isBuffer(chunk)) { if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
throw new TypeError('first argument must be a string or Buffer'); throw new TypeError('first argument must be a string or Buffer');
} }
@ -419,7 +419,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
var len, ret; var len, ret;
if (this.chunkedEncoding) { if (this.chunkedEncoding) {
if (util.isString(chunk) && if (typeof chunk === 'string' &&
encoding !== 'hex' && encoding !== 'hex' &&
encoding !== 'base64' && encoding !== 'base64' &&
encoding !== 'binary') { encoding !== 'binary') {
@ -428,7 +428,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
ret = this._send(chunk, encoding, callback); ret = this._send(chunk, encoding, callback);
} else { } else {
// buffer, or a non-toString-friendly encoding // buffer, or a non-toString-friendly encoding
if (util.isString(chunk)) if (typeof chunk === 'string')
len = Buffer.byteLength(chunk, encoding); len = Buffer.byteLength(chunk, encoding);
else else
len = chunk.length; len = chunk.length;
@ -458,7 +458,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) {
OutgoingMessage.prototype.addTrailers = function(headers) { OutgoingMessage.prototype.addTrailers = function(headers) {
this._trailer = ''; this._trailer = '';
var keys = Object.keys(headers); var keys = Object.keys(headers);
var isArray = util.isArray(headers); var isArray = Array.isArray(headers);
var field, value; var field, value;
for (var i = 0, l = keys.length; i < l; i++) { for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i]; var key = keys[i];
@ -479,15 +479,15 @@ const crlf_buf = new Buffer('\r\n');
OutgoingMessage.prototype.end = function(data, encoding, callback) { OutgoingMessage.prototype.end = function(data, encoding, callback) {
if (util.isFunction(data)) { if (typeof data === 'function') {
callback = data; callback = data;
data = null; data = null;
} else if (util.isFunction(encoding)) { } else if (typeof encoding === 'function') {
callback = encoding; callback = encoding;
encoding = null; encoding = null;
} }
if (data && !util.isString(data) && !util.isBuffer(data)) { if (data && typeof data !== 'string' && !(data instanceof Buffer)) {
throw new TypeError('first argument must be a string or Buffer'); throw new TypeError('first argument must be a string or Buffer');
} }
@ -500,10 +500,9 @@ OutgoingMessage.prototype.end = function(data, encoding, callback) {
self.emit('finish'); self.emit('finish');
} }
if (util.isFunction(callback)) if (typeof callback === 'function')
this.once('finish', callback); this.once('finish', callback);
if (!this._header) { if (!this._header) {
this._implicitHeader(); this._implicitHeader();
} }

6
lib/_http_server.js

@ -153,7 +153,7 @@ ServerResponse.prototype._implicitHeader = function() {
ServerResponse.prototype.writeHead = function(statusCode, reason, obj) { ServerResponse.prototype.writeHead = function(statusCode, reason, obj) {
var headers; var headers;
if (util.isString(reason)) { if (typeof reason === 'string') {
// writeHead(statusCode, reasonPhrase[, headers]) // writeHead(statusCode, reasonPhrase[, headers])
this.statusMessage = reason; this.statusMessage = reason;
} else { } else {
@ -297,7 +297,7 @@ function connectionListener(socket) {
parser.incoming = null; parser.incoming = null;
// Propagate headers limit from server instance to parser // Propagate headers limit from server instance to parser
if (util.isNumber(this.maxHeadersCount)) { if (typeof this.maxHeadersCount === 'number') {
parser.maxHeaderPairs = this.maxHeadersCount << 1; parser.maxHeaderPairs = this.maxHeadersCount << 1;
} else { } else {
// Set default value because parser may be reused from FreeList // Set default value because parser may be reused from FreeList
@ -455,7 +455,7 @@ function connectionListener(socket) {
} }
} }
if (!util.isUndefined(req.headers.expect) && if (req.headers.expect !== undefined &&
(req.httpVersionMajor == 1 && req.httpVersionMinor == 1) && (req.httpVersionMajor == 1 && req.httpVersionMinor == 1) &&
continueExpression.test(req.headers['expect'])) { continueExpression.test(req.headers['expect'])) {
res._expect_continue = true; res._expect_continue = true;

20
lib/_stream_readable.js

@ -95,7 +95,7 @@ function Readable(options) {
Readable.prototype.push = function(chunk, encoding) { Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState; var state = this._readableState;
if (util.isString(chunk) && !state.objectMode) { if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding; encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) { if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding); chunk = new Buffer(chunk, encoding);
@ -209,7 +209,7 @@ function howMuchToRead(n, state) {
if (state.objectMode) if (state.objectMode)
return n === 0 ? 0 : 1; return n === 0 ? 0 : 1;
if (util.isNull(n) || isNaN(n)) { if (n === null || isNaN(n)) {
// only flow one buffer at a time // only flow one buffer at a time
if (state.flowing && state.buffer.length) if (state.flowing && state.buffer.length)
return state.buffer[0].length; return state.buffer[0].length;
@ -245,7 +245,7 @@ Readable.prototype.read = function(n) {
var state = this._readableState; var state = this._readableState;
var nOrig = n; var nOrig = n;
if (!util.isNumber(n) || n > 0) if (typeof n !== 'number' || n > 0)
state.emittedReadable = false; state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we // if we're doing read(0) to trigger a readable event, but we
@ -333,7 +333,7 @@ Readable.prototype.read = function(n) {
else else
ret = null; ret = null;
if (util.isNull(ret)) { if (ret === null) {
state.needReadable = true; state.needReadable = true;
n = 0; n = 0;
} }
@ -349,7 +349,7 @@ Readable.prototype.read = function(n) {
if (nOrig !== n && state.ended && state.length === 0) if (nOrig !== n && state.ended && state.length === 0)
endReadable(this); endReadable(this);
if (!util.isNull(ret)) if (ret !== null)
this.emit('data', ret); this.emit('data', ret);
return ret; return ret;
@ -357,9 +357,10 @@ Readable.prototype.read = function(n) {
function chunkInvalid(state, chunk) { function chunkInvalid(state, chunk) {
var er = null; var er = null;
if (!util.isBuffer(chunk) && if (!(chunk instanceof Buffer) &&
!util.isString(chunk) && typeof chunk !== 'string' &&
!util.isNullOrUndefined(chunk) && chunk !== null &&
chunk !== undefined &&
!state.objectMode) { !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk'); er = new TypeError('Invalid non-string/buffer chunk');
} }
@ -757,7 +758,6 @@ Readable.prototype.wrap = function(stream) {
chunk = state.decoder.write(chunk); chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode // don't skip over falsy values in objectMode
//if (state.objectMode && util.isNullOrUndefined(chunk))
if (state.objectMode && (chunk === null || chunk === undefined)) if (state.objectMode && (chunk === null || chunk === undefined))
return; return;
else if (!state.objectMode && (!chunk || !chunk.length)) else if (!state.objectMode && (!chunk || !chunk.length))
@ -773,7 +773,7 @@ Readable.prototype.wrap = function(stream) {
// proxy all the other methods. // proxy all the other methods.
// important when wrapping filters and duplexes. // important when wrapping filters and duplexes.
for (var i in stream) { for (var i in stream) {
if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function(method) { return function() { this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments); return stream[method].apply(stream, arguments);
}}(i); }}(i);

6
lib/_stream_transform.js

@ -72,7 +72,7 @@ function afterTransform(stream, er, data) {
ts.writechunk = null; ts.writechunk = null;
ts.writecb = null; ts.writecb = null;
if (!util.isNullOrUndefined(data)) if (data !== null && data !== undefined)
stream.push(data); stream.push(data);
if (cb) if (cb)
@ -106,7 +106,7 @@ function Transform(options) {
this._readableState.sync = false; this._readableState.sync = false;
this.once('prefinish', function() { this.once('prefinish', function() {
if (util.isFunction(this._flush)) if (typeof this._flush === 'function')
this._flush(function(er) { this._flush(function(er) {
done(stream, er); done(stream, er);
}); });
@ -154,7 +154,7 @@ Transform.prototype._write = function(chunk, encoding, cb) {
Transform.prototype._read = function(n) { Transform.prototype._read = function(n) {
var ts = this._transformState; var ts = this._transformState;
if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true; ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else { } else {

25
lib/_stream_writable.js

@ -162,9 +162,11 @@ function writeAfterEnd(stream, state, cb) {
// how many bytes or characters. // how many bytes or characters.
function validChunk(stream, state, chunk, cb) { function validChunk(stream, state, chunk, cb) {
var valid = true; var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) && if (!(chunk instanceof Buffer) &&
!util.isNullOrUndefined(chunk) && typeof chunk !== 'string' &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) { !state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk'); var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er); stream.emit('error', er);
@ -180,17 +182,17 @@ Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState; var state = this._writableState;
var ret = false; var ret = false;
if (util.isFunction(encoding)) { if (typeof encoding === 'function') {
cb = encoding; cb = encoding;
encoding = null; encoding = null;
} }
if (util.isBuffer(chunk)) if (chunk instanceof Buffer)
encoding = 'buffer'; encoding = 'buffer';
else if (!encoding) else if (!encoding)
encoding = state.defaultEncoding; encoding = state.defaultEncoding;
if (!util.isFunction(cb)) if (typeof cb !== 'function')
cb = nop; cb = nop;
if (state.ended) if (state.ended)
@ -236,7 +238,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
function decodeChunk(state, chunk, encoding) { function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && if (!state.objectMode &&
state.decodeStrings !== false && state.decodeStrings !== false &&
util.isString(chunk)) { typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding); chunk = new Buffer(chunk, encoding);
} }
return chunk; return chunk;
@ -247,7 +249,8 @@ function decodeChunk(state, chunk, encoding) {
// If we return false, then we need a drain event, so set that flag. // If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) { function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding); chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
if (chunk instanceof Buffer)
encoding = 'buffer'; encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length; var len = state.objectMode ? 1 : chunk.length;
@ -418,16 +421,16 @@ Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) { Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState; var state = this._writableState;
if (util.isFunction(chunk)) { if (typeof chunk === 'function') {
cb = chunk; cb = chunk;
chunk = null; chunk = null;
encoding = null; encoding = null;
} else if (util.isFunction(encoding)) { } else if (typeof encoding === 'function') {
cb = encoding; cb = encoding;
encoding = null; encoding = null;
} }
if (!util.isNullOrUndefined(chunk)) if (chunk !== null && chunk !== undefined)
this.write(chunk, encoding); this.write(chunk, encoding);
// .end() fully uncorks // .end() fully uncorks

7
lib/_tls_common.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
const util = require('util');
const constants = require('constants'); const constants = require('constants');
const tls = require('tls'); const tls = require('tls');
@ -47,7 +46,7 @@ exports.createSecureContext = function createSecureContext(options, context) {
// NOTE: It's important to add CA before the cert to be able to load // NOTE: It's important to add CA before the cert to be able to load
// cert's issuer in C++ code. // cert's issuer in C++ code.
if (options.ca) { if (options.ca) {
if (util.isArray(options.ca)) { if (Array.isArray(options.ca)) {
for (var i = 0, len = options.ca.length; i < len; i++) { for (var i = 0, len = options.ca.length; i < len; i++) {
c.context.addCACert(options.ca[i]); c.context.addCACert(options.ca[i]);
} }
@ -95,7 +94,7 @@ exports.createSecureContext = function createSecureContext(options, context) {
else else
c.context.setCiphers(tls.DEFAULT_CIPHERS); c.context.setCiphers(tls.DEFAULT_CIPHERS);
if (util.isUndefined(options.ecdhCurve)) if (options.ecdhCurve === undefined)
c.context.setECDHCurve(tls.DEFAULT_ECDH_CURVE); c.context.setECDHCurve(tls.DEFAULT_ECDH_CURVE);
else if (options.ecdhCurve) else if (options.ecdhCurve)
c.context.setECDHCurve(options.ecdhCurve); c.context.setECDHCurve(options.ecdhCurve);
@ -103,7 +102,7 @@ exports.createSecureContext = function createSecureContext(options, context) {
if (options.dhparam) c.context.setDHParam(options.dhparam); if (options.dhparam) c.context.setDHParam(options.dhparam);
if (options.crl) { if (options.crl) {
if (util.isArray(options.crl)) { if (Array.isArray(options.crl)) {
for (var i = 0, len = options.crl.length; i < len; i++) { for (var i = 0, len = options.crl.length; i < len; i++) {
c.context.addCRL(options.crl[i]); c.context.addCRL(options.crl[i]);
} }

14
lib/_tls_legacy.js

@ -36,7 +36,7 @@ SlabBuffer.prototype.use = function use(context, fn, size) {
var actualSize = this.remaining; var actualSize = this.remaining;
if (!util.isNull(size)) actualSize = Math.min(size, actualSize); if (size !== null) actualSize = Math.min(size, actualSize);
var bytes = fn.call(context, this.pool, this.offset, actualSize); var bytes = fn.call(context, this.pool, this.offset, actualSize);
if (bytes > 0) { if (bytes > 0) {
@ -72,7 +72,7 @@ function CryptoStream(pair, options) {
this._finished = false; this._finished = false;
this._opposite = null; this._opposite = null;
if (util.isNull(slabBuffer)) slabBuffer = new SlabBuffer(); if (slabBuffer === null) slabBuffer = new SlabBuffer();
this._buffer = slabBuffer; this._buffer = slabBuffer;
this.once('finish', onCryptoStreamFinish); this.once('finish', onCryptoStreamFinish);
@ -142,7 +142,7 @@ CryptoStream.prototype.init = function init() {
CryptoStream.prototype._write = function write(data, encoding, cb) { CryptoStream.prototype._write = function write(data, encoding, cb) {
assert(util.isNull(this._pending)); assert(this._pending === null);
// Black-hole data // Black-hole data
if (!this.pair.ssl) return cb(null); if (!this.pair.ssl) return cb(null);
@ -189,7 +189,7 @@ CryptoStream.prototype._write = function write(data, encoding, cb) {
// Invoke callback only when all data read from opposite stream // Invoke callback only when all data read from opposite stream
if (this._opposite._halfRead) { if (this._opposite._halfRead) {
assert(util.isNull(this._sslOutCb)); assert(this._sslOutCb === null);
this._sslOutCb = cb; this._sslOutCb = cb;
} else { } else {
cb(null); cb(null);
@ -288,8 +288,8 @@ CryptoStream.prototype._read = function read(size) {
} }
// Try writing pending data // Try writing pending data
if (!util.isNull(this._pending)) this._writePending(); if (this._pending !== null) this._writePending();
if (!util.isNull(this._opposite._pending)) this._opposite._writePending(); if (this._opposite._pending !== null) this._opposite._writePending();
if (bytesRead === 0) { if (bytesRead === 0) {
// EOF when cleartext has finished and we have nothing to read // EOF when cleartext has finished and we have nothing to read
@ -398,7 +398,7 @@ CryptoStream.prototype.end = function(chunk, encoding) {
} }
// Write pending data first // Write pending data first
if (!util.isNull(this._pending)) this._writePending(); if (this._pending !== null) this._writePending();
this.writable = false; this.writable = false;

21
lib/_tls_wrap.js

@ -447,7 +447,7 @@ TLSSocket.prototype.setServername = function(name) {
}; };
TLSSocket.prototype.setSession = function(session) { TLSSocket.prototype.setSession = function(session) {
if (util.isString(session)) if (typeof session === 'string')
session = new Buffer(session, 'binary'); session = new Buffer(session, 'binary');
this.ssl.setSession(session); this.ssl.setSession(session);
}; };
@ -554,10 +554,11 @@ TLSSocket.prototype.getCipher = function(err) {
// //
function Server(/* [options], listener */) { function Server(/* [options], listener */) {
var options, listener; var options, listener;
if (util.isObject(arguments[0])) {
if (arguments[0] !== null && typeof arguments[0] === 'object') {
options = arguments[0]; options = arguments[0];
listener = arguments[1]; listener = arguments[1];
} else if (util.isFunction(arguments[0])) { } else if (typeof arguments[0] === 'function') {
options = {}; options = {};
listener = arguments[0]; listener = arguments[0];
} }
@ -590,7 +591,7 @@ function Server(/* [options], listener */) {
var timeout = options.handshakeTimeout || (120 * 1000); var timeout = options.handshakeTimeout || (120 * 1000);
if (!util.isNumber(timeout)) { if (typeof timeout !== 'number') {
throw new TypeError('handshakeTimeout must be a number'); throw new TypeError('handshakeTimeout must be a number');
} }
@ -676,13 +677,13 @@ Server.prototype._setServerData = function(data) {
Server.prototype.setOptions = function(options) { Server.prototype.setOptions = function(options) {
if (util.isBoolean(options.requestCert)) { if (typeof options.requestCert === 'boolean') {
this.requestCert = options.requestCert; this.requestCert = options.requestCert;
} else { } else {
this.requestCert = false; this.requestCert = false;
} }
if (util.isBoolean(options.rejectUnauthorized)) { if (typeof options.rejectUnauthorized === 'boolean') {
this.rejectUnauthorized = options.rejectUnauthorized; this.rejectUnauthorized = options.rejectUnauthorized;
} else { } else {
this.rejectUnauthorized = false; this.rejectUnauthorized = false;
@ -696,7 +697,7 @@ Server.prototype.setOptions = function(options) {
if (options.secureProtocol) this.secureProtocol = options.secureProtocol; if (options.secureProtocol) this.secureProtocol = options.secureProtocol;
if (options.crl) this.crl = options.crl; if (options.crl) this.crl = options.crl;
if (options.ciphers) this.ciphers = options.ciphers; if (options.ciphers) this.ciphers = options.ciphers;
if (!util.isUndefined(options.ecdhCurve)) if (options.ecdhCurve !== undefined)
this.ecdhCurve = options.ecdhCurve; this.ecdhCurve = options.ecdhCurve;
if (options.dhparam) this.dhparam = options.dhparam; if (options.dhparam) this.dhparam = options.dhparam;
if (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout; if (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout;
@ -734,7 +735,7 @@ function SNICallback(servername, callback) {
var ctx; var ctx;
this.server._contexts.some(function(elem) { this.server._contexts.some(function(elem) {
if (!util.isNull(servername.match(elem[0]))) { if (servername.match(elem[0]) !== null) {
ctx = elem[1]; ctx = elem[1];
return true; return true;
} }
@ -763,9 +764,9 @@ function normalizeConnectArgs(listArgs) {
var options = args[0]; var options = args[0];
var cb = args[1]; var cb = args[1];
if (util.isObject(listArgs[1])) { if (listArgs[1] !== null && typeof listArgs[1] === 'object') {
options = util._extend(options, listArgs[1]); options = util._extend(options, listArgs[1]);
} else if (util.isObject(listArgs[2])) { } else if (listArgs[2] !== null && typeof listArgs[2] === 'object') {
options = util._extend(options, listArgs[2]); options = util._extend(options, listArgs[2]);
} }

14
lib/assert.js

@ -59,7 +59,7 @@ assert.AssertionError = function AssertionError(options) {
util.inherits(assert.AssertionError, Error); util.inherits(assert.AssertionError, Error);
function truncate(s, n) { function truncate(s, n) {
if (util.isString(s)) { if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n); return s.length < n ? s : s.slice(0, n);
} else { } else {
return s; return s;
@ -138,8 +138,7 @@ function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===. // 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) { if (actual === expected) {
return true; return true;
} else if (actual instanceof Buffer && expected instanceof Buffer) {
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false; if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) { for (var i = 0; i < actual.length; i++) {
@ -165,7 +164,8 @@ function _deepEqual(actual, expected) {
// 7.4. Other pairs that do not both pass typeof value == 'object', // 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==. // equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) { } else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return actual == expected; return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is // 7.5 For all other Object pairs, including Array objects, equivalence is
@ -184,7 +184,7 @@ function isArguments(object) {
} }
function objEquiv(a, b) { function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) if (a === null || a === undefined || b === null || b === undefined)
return false; return false;
// an identical 'prototype' property. // an identical 'prototype' property.
if (a.prototype !== b.prototype) return false; if (a.prototype !== b.prototype) return false;
@ -270,11 +270,11 @@ function expectedException(actual, expected) {
function _throws(shouldThrow, block, expected, message) { function _throws(shouldThrow, block, expected, message) {
var actual; var actual;
if (!util.isFunction(block)) { if (typeof block !== 'function') {
throw new TypeError('block must be a function'); throw new TypeError('block must be a function');
} }
if (util.isString(expected)) { if (typeof expected === 'string') {
message = expected; message = expected;
expected = null; expected = null;
} }

40
lib/buffer.js

@ -27,20 +27,20 @@ createPool();
function Buffer(subject, encoding) { function Buffer(subject, encoding) {
if (!util.isBuffer(this)) if (!(this instanceof Buffer))
return new Buffer(subject, encoding); return new Buffer(subject, encoding);
if (util.isNumber(subject)) { if (typeof subject === 'number') {
this.length = +subject; this.length = +subject;
} else if (util.isString(subject)) { } else if (typeof subject === 'string') {
if (!util.isString(encoding) || encoding.length === 0) if (typeof encoding !== 'string' || encoding.length === 0)
encoding = 'utf8'; encoding = 'utf8';
this.length = Buffer.byteLength(subject, encoding); this.length = Buffer.byteLength(subject, encoding);
// Handle Arrays, Buffers, Uint8Arrays or JSON. // Handle Arrays, Buffers, Uint8Arrays or JSON.
} else if (util.isObject(subject)) { } else if (subject !== null && typeof subject === 'object') {
if (subject.type === 'Buffer' && util.isArray(subject.data)) if (subject.type === 'Buffer' && Array.isArray(subject.data))
subject = subject.data; subject = subject.data;
this.length = +subject.length; this.length = +subject.length;
@ -71,11 +71,11 @@ function Buffer(subject, encoding) {
alloc(this, this.length); alloc(this, this.length);
} }
if (util.isNumber(subject)) { if (typeof subject === 'number') {
return; return;
} }
if (util.isString(subject)) { if (typeof subject === 'string') {
// In the case of base64 it's possible that the size of the buffer // In the case of base64 it's possible that the size of the buffer
// allocated was slightly too large. In this case we need to rewrite // allocated was slightly too large. In this case we need to rewrite
// the length to the actual length written. // the length to the actual length written.
@ -88,10 +88,10 @@ function Buffer(subject, encoding) {
poolOffset -= (prevLen - len); poolOffset -= (prevLen - len);
} }
} else if (util.isBuffer(subject)) { } else if (subject instanceof Buffer) {
subject.copy(this, 0, 0, this.length); subject.copy(this, 0, 0, this.length);
} else if (util.isNumber(subject.length) || util.isArray(subject)) { } else if (typeof subject.length === 'number' || Array.isArray(subject)) {
// Really crappy way to handle Uint8Arrays, but V8 doesn't give a simple // Really crappy way to handle Uint8Arrays, but V8 doesn't give a simple
// way to access the data from the C++ API. // way to access the data from the C++ API.
for (var i = 0; i < this.length; i++) for (var i = 0; i < this.length; i++)
@ -130,7 +130,7 @@ buffer.setupBufferJS(NativeBuffer, internal);
// Static methods // Static methods
Buffer.isBuffer = function isBuffer(b) { Buffer.isBuffer = function isBuffer(b) {
return util.isBuffer(b); return b instanceof Buffer;
}; };
@ -165,10 +165,10 @@ Buffer.isEncoding = function(encoding) {
Buffer.concat = function(list, length) { Buffer.concat = function(list, length) {
if (!util.isArray(list)) if (!Array.isArray(list))
throw new TypeError('Usage: Buffer.concat(list[, length])'); throw new TypeError('Usage: Buffer.concat(list[, length])');
if (util.isUndefined(length)) { if (length === undefined) {
length = 0; length = 0;
for (var i = 0; i < list.length; i++) for (var i = 0; i < list.length; i++)
length += list[i].length; length += list[i].length;
@ -223,7 +223,7 @@ Buffer.prototype.toString = function(encoding, start, end) {
var loweredCase = false; var loweredCase = false;
start = start >>> 0; start = start >>> 0;
end = util.isUndefined(end) || end === Infinity ? this.length : end >>> 0; end = end === undefined || end === Infinity ? this.length : end >>> 0;
if (!encoding) encoding = 'utf8'; if (!encoding) encoding = 'utf8';
if (start < 0) start = 0; if (start < 0) start = 0;
@ -341,13 +341,13 @@ const writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
' Use write(string[, offset[, length]][, encoding]) instead.'; ' Use write(string[, offset[, length]][, encoding]) instead.';
Buffer.prototype.write = function(string, offset, length, encoding) { Buffer.prototype.write = function(string, offset, length, encoding) {
// Buffer#write(string); // Buffer#write(string);
if (util.isUndefined(offset)) { if (offset === undefined) {
encoding = 'utf8'; encoding = 'utf8';
length = this.length; length = this.length;
offset = 0; offset = 0;
// Buffer#write(string, encoding) // Buffer#write(string, encoding)
} else if (util.isUndefined(length) && util.isString(offset)) { } else if (length === undefined && typeof offset === 'string') {
encoding = offset; encoding = offset;
length = this.length; length = this.length;
offset = 0; offset = 0;
@ -357,7 +357,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
offset = offset >>> 0; offset = offset >>> 0;
if (isFinite(length)) { if (isFinite(length)) {
length = length >>> 0; length = length >>> 0;
if (util.isUndefined(encoding)) if (encoding === undefined)
encoding = 'utf8'; encoding = 'utf8';
} else { } else {
encoding = length; encoding = length;
@ -383,7 +383,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
} }
var remaining = this.length - offset; var remaining = this.length - offset;
if (util.isUndefined(length) || length > remaining) if (length === undefined || length > remaining)
length = remaining; length = remaining;
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
@ -443,7 +443,7 @@ Buffer.prototype.toJSON = function() {
Buffer.prototype.slice = function(start, end) { Buffer.prototype.slice = function(start, end) {
var len = this.length; var len = this.length;
start = ~~start; start = ~~start;
end = util.isUndefined(end) ? len : ~~end; end = end === undefined ? len : ~~end;
if (start < 0) { if (start < 0) {
start += len; start += len;
@ -468,7 +468,7 @@ Buffer.prototype.slice = function(start, end) {
sliceOnto(this, buf, start, end); sliceOnto(this, buf, start, end);
buf.length = end - start; buf.length = end - start;
if (buf.length > 0) if (buf.length > 0)
buf.parent = util.isUndefined(this.parent) ? this : this.parent; buf.parent = this.parent === undefined ? this : this.parent;
return buf; return buf;
}; };

55
lib/child_process.js

@ -22,7 +22,7 @@ function handleWrapGetter(name, callback) {
Object.defineProperty(handleWraps, name, { Object.defineProperty(handleWraps, name, {
get: function() { get: function() {
if (!util.isUndefined(cons)) return cons; if (cons !== undefined) return cons;
return cons = callback(); return cons = callback();
} }
}); });
@ -295,9 +295,9 @@ function getSocketList(type, slave, key) {
const INTERNAL_PREFIX = 'NODE_'; const INTERNAL_PREFIX = 'NODE_';
function handleMessage(target, message, handle) { function handleMessage(target, message, handle) {
var eventName = 'message'; var eventName = 'message';
if (!util.isNull(message) && if (message !== null &&
util.isObject(message) && typeof message === 'object' &&
util.isString(message.cmd) && typeof message.cmd === 'string' &&
message.cmd.length > INTERNAL_PREFIX.length && message.cmd.length > INTERNAL_PREFIX.length &&
message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) { message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) {
eventName = 'internalMessage'; eventName = 'internalMessage';
@ -353,7 +353,7 @@ function setupChannel(target, channel) {
target.on('internalMessage', function(message, handle) { target.on('internalMessage', function(message, handle) {
// Once acknowledged - continue sending handles. // Once acknowledged - continue sending handles.
if (message.cmd === 'NODE_HANDLE_ACK') { if (message.cmd === 'NODE_HANDLE_ACK') {
assert(util.isArray(target._handleQueue)); assert(Array.isArray(target._handleQueue));
var queue = target._handleQueue; var queue = target._handleQueue;
target._handleQueue = null; target._handleQueue = null;
@ -400,7 +400,7 @@ function setupChannel(target, channel) {
target._send = function(message, handle, swallowErrors) { target._send = function(message, handle, swallowErrors) {
assert(this.connected || this._channel); assert(this.connected || this._channel);
if (util.isUndefined(message)) if (message === undefined)
throw new TypeError('message cannot be undefined'); throw new TypeError('message cannot be undefined');
// package messages with a handle object // package messages with a handle object
@ -538,7 +538,7 @@ exports.fork = function(modulePath /*, args, options*/) {
// Get options and args arguments. // Get options and args arguments.
var options, args, execArgv; var options, args, execArgv;
if (util.isArray(arguments[1])) { if (Array.isArray(arguments[1])) {
args = arguments[1]; args = arguments[1];
options = util._extend({}, arguments[2]); options = util._extend({}, arguments[2]);
} else { } else {
@ -583,7 +583,7 @@ exports._forkChild = function(fd) {
function normalizeExecArgs(command /*, options, callback */) { function normalizeExecArgs(command /*, options, callback */) {
var file, args, options, callback; var file, args, options, callback;
if (util.isFunction(arguments[1])) { if (typeof arguments[1] === 'function') {
options = undefined; options = undefined;
callback = arguments[1]; callback = arguments[1];
} else { } else {
@ -638,11 +638,11 @@ exports.execFile = function(file /* args, options, callback */) {
// Parse the parameters. // Parse the parameters.
if (util.isFunction(arguments[arguments.length - 1])) { if (typeof arguments[arguments.length - 1] === 'function') {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
} }
if (util.isArray(arguments[1])) { if (Array.isArray(arguments[1])) {
args = arguments[1]; args = arguments[1];
options = util._extend(options, arguments[2]); options = util._extend(options, arguments[2]);
} else { } else {
@ -806,14 +806,14 @@ function _validateStdio(stdio, sync) {
ipcFd; ipcFd;
// Replace shortcut with an array // Replace shortcut with an array
if (util.isString(stdio)) { if (typeof stdio === 'string') {
switch (stdio) { switch (stdio) {
case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break; case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break;
case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break;
case 'inherit': stdio = [0, 1, 2]; break; case 'inherit': stdio = [0, 1, 2]; break;
default: throw new TypeError('Incorrect value of stdio option: ' + stdio); default: throw new TypeError('Incorrect value of stdio option: ' + stdio);
} }
} else if (!util.isArray(stdio)) { } else if (!Array.isArray(stdio)) {
throw new TypeError('Incorrect value of stdio option: ' + throw new TypeError('Incorrect value of stdio option: ' +
util.inspect(stdio)); util.inspect(stdio));
} }
@ -837,13 +837,13 @@ function _validateStdio(stdio, sync) {
} }
// Defaults // Defaults
if (util.isNullOrUndefined(stdio)) { if (stdio === null || stdio === undefined) {
stdio = i < 3 ? 'pipe' : 'ignore'; stdio = i < 3 ? 'pipe' : 'ignore';
} }
if (stdio === null || stdio === 'ignore') { if (stdio === null || stdio === 'ignore') {
acc.push({type: 'ignore'}); acc.push({type: 'ignore'});
} else if (stdio === 'pipe' || util.isNumber(stdio) && stdio < 0) { } else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) {
var a = { var a = {
type: 'pipe', type: 'pipe',
readable: i === 0, readable: i === 0,
@ -855,7 +855,7 @@ function _validateStdio(stdio, sync) {
acc.push(a); acc.push(a);
} else if (stdio === 'ipc') { } else if (stdio === 'ipc') {
if (sync || !util.isUndefined(ipc)) { if (sync || ipc !== undefined) {
// Cleanup previously created pipes // Cleanup previously created pipes
cleanup(); cleanup();
if (!sync) if (!sync)
@ -877,7 +877,7 @@ function _validateStdio(stdio, sync) {
type: 'inherit', type: 'inherit',
fd: i fd: i
}); });
} else if (util.isNumber(stdio) || util.isNumber(stdio.fd)) { } else if (typeof stdio === 'number' || typeof stdio.fd === 'number') {
acc.push({ acc.push({
type: 'fd', type: 'fd',
fd: stdio.fd || stdio fd: stdio.fd || stdio
@ -893,7 +893,7 @@ function _validateStdio(stdio, sync) {
wrapType: getHandleWrapType(handle), wrapType: getHandleWrapType(handle),
handle: handle handle: handle
}); });
} else if (util.isBuffer(stdio) || util.isString(stdio)) { } else if (stdio instanceof Buffer || typeof stdio === 'string') {
if (!sync) { if (!sync) {
cleanup(); cleanup();
throw new TypeError('Asynchronous forks do not support Buffer input: ' + throw new TypeError('Asynchronous forks do not support Buffer input: ' +
@ -919,7 +919,8 @@ function normalizeSpawnArguments(file /*, args, options*/) {
if (Array.isArray(arguments[1])) { if (Array.isArray(arguments[1])) {
args = arguments[1].slice(0); args = arguments[1].slice(0);
options = arguments[2]; options = arguments[2];
} else if (arguments[1] !== undefined && !util.isObject(arguments[1])) { } else if (arguments[1] !== undefined &&
(arguments[1] === null || typeof arguments[1] !== 'object')) {
throw new TypeError('Incorrect value of args option'); throw new TypeError('Incorrect value of args option');
} else { } else {
args = []; args = [];
@ -928,7 +929,7 @@ function normalizeSpawnArguments(file /*, args, options*/) {
if (options === undefined) if (options === undefined)
options = {}; options = {};
else if (!util.isObject(options)) else if (options === null || typeof options !== 'object')
throw new TypeError('options argument must be an object'); throw new TypeError('options argument must be an object');
options = util._extend({}, options); options = util._extend({}, options);
@ -1089,7 +1090,7 @@ ChildProcess.prototype.spawn = function(options) {
ipcFd = stdio.ipcFd; ipcFd = stdio.ipcFd;
stdio = options.stdio = stdio.stdio; stdio = options.stdio = stdio.stdio;
if (!util.isUndefined(ipc)) { if (ipc !== undefined) {
// Let child process know about opened IPC channel // Let child process know about opened IPC channel
options.envPairs = options.envPairs || []; options.envPairs = options.envPairs || [];
options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd);
@ -1150,19 +1151,19 @@ ChildProcess.prototype.spawn = function(options) {
} }
}); });
this.stdin = stdio.length >= 1 && !util.isUndefined(stdio[0].socket) ? this.stdin = stdio.length >= 1 && stdio[0].socket !== undefined ?
stdio[0].socket : null; stdio[0].socket : null;
this.stdout = stdio.length >= 2 && !util.isUndefined(stdio[1].socket) ? this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ?
stdio[1].socket : null; stdio[1].socket : null;
this.stderr = stdio.length >= 3 && !util.isUndefined(stdio[2].socket) ? this.stderr = stdio.length >= 3 && stdio[2].socket !== undefined ?
stdio[2].socket : null; stdio[2].socket : null;
this.stdio = stdio.map(function(stdio) { this.stdio = stdio.map(function(stdio) {
return util.isUndefined(stdio.socket) ? null : stdio.socket; return stdio.socket === undefined ? null : stdio.socket;
}); });
// Add .send() method and start listening for IPC data // Add .send() method and start listening for IPC data
if (!util.isUndefined(ipc)) setupChannel(this, ipc); if (ipc !== undefined) setupChannel(this, ipc);
return err; return err;
}; };
@ -1183,7 +1184,7 @@ ChildProcess.prototype.kill = function(sig) {
signal = constants[sig]; signal = constants[sig];
} }
if (util.isUndefined(signal)) { if (signal === undefined) {
throw new Error('Unknown signal: ' + sig); throw new Error('Unknown signal: ' + sig);
} }
@ -1262,7 +1263,7 @@ function spawnSync(/*file, args, options*/) {
var pipe = options.stdio[i] = util._extend({}, options.stdio[i]); var pipe = options.stdio[i] = util._extend({}, options.stdio[i]);
if (Buffer.isBuffer(input)) if (Buffer.isBuffer(input))
pipe.input = input; pipe.input = input;
else if (util.isString(input)) else if (typeof input === 'string')
pipe.input = new Buffer(input, options.encoding); pipe.input = new Buffer(input, options.encoding);
else else
throw new TypeError(util.format( throw new TypeError(util.format(

22
lib/cluster.js

@ -22,7 +22,7 @@ function Worker(options) {
EventEmitter.call(this); EventEmitter.call(this);
if (!util.isObject(options)) if (options === null || typeof options !== 'object')
options = {}; options = {};
this.suicide = undefined; this.suicide = undefined;
@ -68,7 +68,7 @@ function SharedHandle(key, address, port, addressType, backlog, fd) {
else else
rval = net._createServerHandle(address, port, addressType, fd); rval = net._createServerHandle(address, port, addressType, fd);
if (util.isNumber(rval)) if (typeof rval === 'number')
this.errno = rval; this.errno = rval;
else else
this.handle = rval; this.handle = rval;
@ -135,7 +135,7 @@ RoundRobinHandle.prototype.add = function(worker, send) {
self.handoff(worker); // In case there are connections pending. self.handoff(worker); // In case there are connections pending.
} }
if (util.isNull(this.server)) return done(); if (this.server === null) return done();
// Still busy binding. // Still busy binding.
this.server.once('listening', done); this.server.once('listening', done);
this.server.once('error', function(err) { this.server.once('error', function(err) {
@ -170,7 +170,7 @@ RoundRobinHandle.prototype.handoff = function(worker) {
return; // Worker is closing (or has closed) the server. return; // Worker is closing (or has closed) the server.
} }
var handle = this.handles.shift(); var handle = this.handles.shift();
if (util.isUndefined(handle)) { if (handle === undefined) {
this.free.push(worker); // Add to ready queue again. this.free.push(worker); // Add to ready queue again.
return; return;
} }
@ -203,7 +203,7 @@ function masterInit() {
'rr': SCHED_RR 'rr': SCHED_RR
}[process.env.NODE_CLUSTER_SCHED_POLICY]; }[process.env.NODE_CLUSTER_SCHED_POLICY];
if (util.isUndefined(schedulingPolicy)) { if (schedulingPolicy === undefined) {
// FIXME Round-robin doesn't perform well on Windows right now due to the // FIXME Round-robin doesn't perform well on Windows right now due to the
// way IOCP is wired up. Bert is going to fix that, eventually. // way IOCP is wired up. Bert is going to fix that, eventually.
schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR;
@ -438,7 +438,7 @@ function masterInit() {
message.fd]; message.fd];
var key = args.join(':'); var key = args.join(':');
var handle = handles[key]; var handle = handles[key];
if (util.isUndefined(handle)) { if (handle === undefined) {
var constructor = RoundRobinHandle; var constructor = RoundRobinHandle;
// UDP is exempt from round-robin connection balancing for what should // UDP is exempt from round-robin connection balancing for what should
// be obvious reasons: it's connectionless. There is nothing to send to // be obvious reasons: it's connectionless. There is nothing to send to
@ -562,7 +562,7 @@ function workerInit() {
delete handles[key]; delete handles[key];
return close.apply(this, arguments); return close.apply(this, arguments);
}; };
assert(util.isUndefined(handles[key])); assert(handles[key] === undefined);
handles[key] = handle; handles[key] = handle;
cb(message.errno, handle); cb(message.errno, handle);
} }
@ -586,7 +586,7 @@ function workerInit() {
// the ack by the master process in which we can still receive handles. // the ack by the master process in which we can still receive handles.
// onconnection() below handles that by sending those handles back to // onconnection() below handles that by sending those handles back to
// the master. // the master.
if (util.isUndefined(key)) return; if (key === undefined) return;
send({ act: 'close', key: key }); send({ act: 'close', key: key });
delete handles[key]; delete handles[key];
key = undefined; key = undefined;
@ -607,7 +607,7 @@ function workerInit() {
if (message.sockname) { if (message.sockname) {
handle.getsockname = getsockname; // TCP handles only. handle.getsockname = getsockname; // TCP handles only.
} }
assert(util.isUndefined(handles[key])); assert(handles[key] === undefined);
handles[key] = handle; handles[key] = handle;
cb(0, handle); cb(0, handle);
} }
@ -616,7 +616,7 @@ function workerInit() {
function onconnection(message, handle) { function onconnection(message, handle) {
var key = message.key; var key = message.key;
var server = handles[key]; var server = handles[key];
var accepted = !util.isUndefined(server); var accepted = server !== undefined;
send({ ack: message.seq, accepted: accepted }); send({ ack: message.seq, accepted: accepted });
if (accepted) server.onconnection(0, handle); if (accepted) server.onconnection(0, handle);
} }
@ -664,7 +664,7 @@ function internal(worker, cb) {
return function(message, handle) { return function(message, handle) {
if (message.cmd !== 'NODE_CLUSTER') return; if (message.cmd !== 'NODE_CLUSTER') return;
var fn = cb; var fn = cb;
if (!util.isUndefined(message.ack)) { if (message.ack !== undefined) {
fn = callbacks[message.ack]; fn = callbacks[message.ack];
delete callbacks[message.ack]; delete callbacks[message.ack];
} }

2
lib/console.js

@ -6,7 +6,7 @@ function Console(stdout, stderr) {
if (!(this instanceof Console)) { if (!(this instanceof Console)) {
return new Console(stdout, stderr); return new Console(stdout, stderr);
} }
if (!stdout || !util.isFunction(stdout.write)) { if (!stdout || typeof stdout.write !== 'function') {
throw new TypeError('Console expects a writable stream instance'); throw new TypeError('Console expects a writable stream instance');
} }
if (!stderr) { if (!stderr) {

16
lib/crypto.js

@ -25,7 +25,7 @@ const DH_GENERATOR = 2;
// to break them unnecessarily. // to break them unnecessarily.
function toBuf(str, encoding) { function toBuf(str, encoding) {
encoding = encoding || 'binary'; encoding = encoding || 'binary';
if (util.isString(str)) { if (typeof str === 'string') {
if (encoding === 'buffer') if (encoding === 'buffer')
encoding = 'binary'; encoding = 'binary';
str = new Buffer(str, encoding); str = new Buffer(str, encoding);
@ -92,7 +92,7 @@ Hash.prototype._flush = function(callback) {
Hash.prototype.update = function(data, encoding) { Hash.prototype.update = function(data, encoding) {
encoding = encoding || exports.DEFAULT_ENCODING; encoding = encoding || exports.DEFAULT_ENCODING;
if (encoding === 'buffer' && util.isString(data)) if (encoding === 'buffer' && typeof data === 'string')
encoding = 'binary'; encoding = 'binary';
this._handle.update(data, encoding); this._handle.update(data, encoding);
return this; return this;
@ -369,7 +369,7 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) {
if (!(this instanceof DiffieHellman)) if (!(this instanceof DiffieHellman))
return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding); return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding);
if (!util.isBuffer(sizeOrKey) && if (!(sizeOrKey instanceof Buffer) &&
typeof sizeOrKey !== 'number' && typeof sizeOrKey !== 'number' &&
typeof sizeOrKey !== 'string') typeof sizeOrKey !== 'string')
throw new TypeError('First argument should be number, string or Buffer'); throw new TypeError('First argument should be number, string or Buffer');
@ -513,7 +513,7 @@ DiffieHellman.prototype.setPrivateKey = function(key, encoding) {
function ECDH(curve) { function ECDH(curve) {
if (!util.isString(curve)) if (typeof curve !== 'string')
throw new TypeError('curve should be a string'); throw new TypeError('curve should be a string');
this._handle = new binding.ECDH(curve); this._handle = new binding.ECDH(curve);
@ -566,12 +566,12 @@ exports.pbkdf2 = function(password,
keylen, keylen,
digest, digest,
callback) { callback) {
if (util.isFunction(digest)) { if (typeof digest === 'function') {
callback = digest; callback = digest;
digest = undefined; digest = undefined;
} }
if (!util.isFunction(callback)) if (typeof callback !== 'function')
throw new Error('No callback provided to pbkdf2'); throw new Error('No callback provided to pbkdf2');
return pbkdf2(password, salt, iterations, keylen, digest, callback); return pbkdf2(password, salt, iterations, keylen, digest, callback);
@ -632,10 +632,10 @@ Certificate.prototype.exportChallenge = function(object, encoding) {
exports.setEngine = function setEngine(id, flags) { exports.setEngine = function setEngine(id, flags) {
if (!util.isString(id)) if (typeof id !== 'string')
throw new TypeError('id should be a string'); throw new TypeError('id should be a string');
if (flags && !util.isNumber(flags)) if (flags && typeof flags !== 'number')
throw new TypeError('flags should be a number, if present'); throw new TypeError('flags should be a number, if present');
flags = flags >>> 0; flags = flags >>> 0;

24
lib/dgram.js

@ -61,7 +61,7 @@ function newHandle(type) {
exports._createSocketHandle = function(address, port, addressType, fd) { exports._createSocketHandle = function(address, port, addressType, fd) {
// Opening an existing fd is not supported for UDP handles. // Opening an existing fd is not supported for UDP handles.
assert(!util.isNumber(fd) || fd < 0); assert(typeof fd !== 'number' || fd < 0);
var handle = newHandle(addressType); var handle = newHandle(addressType);
@ -97,7 +97,7 @@ function Socket(type, listener) {
// If true - UV_UDP_REUSEADDR flag will be set // If true - UV_UDP_REUSEADDR flag will be set
this._reuseAddr = options && options.reuseAddr; this._reuseAddr = options && options.reuseAddr;
if (util.isFunction(listener)) if (typeof listener === 'function')
this.on('message', listener); this.on('message', listener);
} }
util.inherits(Socket, events.EventEmitter); util.inherits(Socket, events.EventEmitter);
@ -143,7 +143,7 @@ Socket.prototype.bind = function(port /*, address, callback*/) {
this._bindState = BIND_STATE_BINDING; this._bindState = BIND_STATE_BINDING;
if (util.isFunction(arguments[arguments.length - 1])) if (typeof arguments[arguments.length - 1] === 'function')
self.once('listening', arguments[arguments.length - 1]); self.once('listening', arguments[arguments.length - 1]);
const UDP = process.binding('udp_wrap').UDP; const UDP = process.binding('udp_wrap').UDP;
@ -156,12 +156,12 @@ Socket.prototype.bind = function(port /*, address, callback*/) {
var address; var address;
var exclusive; var exclusive;
if (util.isObject(port)) { if (port !== null && typeof port === 'object') {
address = port.address || ''; address = port.address || '';
exclusive = !!port.exclusive; exclusive = !!port.exclusive;
port = port.port; port = port.port;
} else { } else {
address = util.isFunction(arguments[1]) ? '' : arguments[1]; address = typeof arguments[1] === 'function' ? '' : arguments[1];
exclusive = false; exclusive = false;
} }
@ -225,10 +225,10 @@ Socket.prototype.sendto = function(buffer,
port, port,
address, address,
callback) { callback) {
if (!util.isNumber(offset) || !util.isNumber(length)) if (typeof offset !== 'number' || typeof length !== 'number')
throw new Error('send takes offset and length as args 2 and 3'); throw new Error('send takes offset and length as args 2 and 3');
if (!util.isString(address)) if (typeof address !== 'string')
throw new Error(this.type + ' sockets must send to port, address'); throw new Error(this.type + ' sockets must send to port, address');
this.send(buffer, offset, length, port, address, callback); this.send(buffer, offset, length, port, address, callback);
@ -243,10 +243,10 @@ Socket.prototype.send = function(buffer,
callback) { callback) {
var self = this; var self = this;
if (util.isString(buffer)) if (typeof buffer === 'string')
buffer = new Buffer(buffer); buffer = new Buffer(buffer);
if (!util.isBuffer(buffer)) if (!(buffer instanceof Buffer))
throw new TypeError('First argument must be a buffer or string.'); throw new TypeError('First argument must be a buffer or string.');
offset = offset | 0; offset = offset | 0;
@ -272,7 +272,7 @@ Socket.prototype.send = function(buffer,
// Normalize callback so it's either a function or undefined but not anything // Normalize callback so it's either a function or undefined but not anything
// else. // else.
if (!util.isFunction(callback)) if (typeof callback !== 'function')
callback = undefined; callback = undefined;
self._healthCheck(); self._healthCheck();
@ -378,7 +378,7 @@ Socket.prototype.setBroadcast = function(arg) {
Socket.prototype.setTTL = function(arg) { Socket.prototype.setTTL = function(arg) {
if (!util.isNumber(arg)) { if (typeof arg !== 'number') {
throw new TypeError('Argument must be a number'); throw new TypeError('Argument must be a number');
} }
@ -392,7 +392,7 @@ Socket.prototype.setTTL = function(arg) {
Socket.prototype.setMulticastTTL = function(arg) { Socket.prototype.setMulticastTTL = function(arg) {
if (!util.isNumber(arg)) { if (typeof arg !== 'number') {
throw new TypeError('Argument must be a number'); throw new TypeError('Argument must be a number');
} }

14
lib/dns.js

@ -53,7 +53,7 @@ function errnoException(err, syscall, hostname) {
// callback.immediately = true; // callback.immediately = true;
// } // }
function makeAsync(callback) { function makeAsync(callback) {
if (!util.isFunction(callback)) { if (typeof callback !== 'function') {
return callback; return callback;
} }
return function asyncCallback() { return function asyncCallback() {
@ -96,7 +96,7 @@ exports.lookup = function lookup(hostname, options, callback) {
family = 0; family = 0;
} else if (typeof callback !== 'function') { } else if (typeof callback !== 'function') {
throw TypeError('invalid arguments: callback must be passed'); throw TypeError('invalid arguments: callback must be passed');
} else if (util.isObject(options)) { } else if (options !== null && typeof options === 'object') {
hints = options.hints >>> 0; hints = options.hints >>> 0;
family = options.family >>> 0; family = options.family >>> 0;
@ -192,9 +192,9 @@ function resolver(bindingName) {
var binding = cares[bindingName]; var binding = cares[bindingName];
return function query(name, callback) { return function query(name, callback) {
if (!util.isString(name)) { if (typeof name !== 'string') {
throw new Error('Name must be a string'); throw new Error('Name must be a string');
} else if (!util.isFunction(callback)) { } else if (typeof callback !== 'function') {
throw new Error('Callback must be a function'); throw new Error('Callback must be a function');
} }
@ -228,17 +228,17 @@ exports.reverse = resolveMap.PTR = resolver('getHostByAddr');
exports.resolve = function(hostname, type_, callback_) { exports.resolve = function(hostname, type_, callback_) {
var resolver, callback; var resolver, callback;
if (util.isString(type_)) { if (typeof type_ === 'string') {
resolver = resolveMap[type_]; resolver = resolveMap[type_];
callback = callback_; callback = callback_;
} else if (util.isFunction(type_)) { } else if (typeof type_ === 'function') {
resolver = exports.resolve4; resolver = exports.resolve4;
callback = type_; callback = type_;
} else { } else {
throw new Error('Type must be a string'); throw new Error('Type must be a string');
} }
if (util.isFunction(resolver)) { if (typeof resolver === 'function') {
return resolver(hostname, callback); return resolver(hostname, callback);
} else { } else {
throw new Error('Unknown type "' + type_ + '"'); throw new Error('Unknown type "' + type_ + '"');

35
lib/events.js

@ -1,7 +1,6 @@
'use strict'; 'use strict';
var domain; var domain;
const util = require('util');
function EventEmitter() { function EventEmitter() {
EventEmitter.init.call(this); EventEmitter.init.call(this);
@ -40,14 +39,14 @@ EventEmitter.init = function() {
// Obviously not all Emitters should be limited to 10. This function allows // Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited. // that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (!util.isNumber(n) || n < 0 || isNaN(n)) if (typeof n !== 'number' || n < 0 || isNaN(n))
throw TypeError('n must be a positive number'); throw TypeError('n must be a positive number');
this._maxListeners = n; this._maxListeners = n;
return this; return this;
}; };
function $getMaxListeners(that) { function $getMaxListeners(that) {
if (util.isUndefined(that._maxListeners)) if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners; return EventEmitter.defaultMaxListeners;
return that._maxListeners; return that._maxListeners;
} }
@ -82,13 +81,13 @@ EventEmitter.prototype.emit = function emit(type) {
handler = this._events[type]; handler = this._events[type];
if (util.isUndefined(handler)) if (handler === undefined)
return false; return false;
if (this.domain && this !== process) if (this.domain && this !== process)
this.domain.enter(); this.domain.enter();
if (util.isFunction(handler)) { if (typeof handler === 'function') {
switch (arguments.length) { switch (arguments.length) {
// fast cases // fast cases
case 1: case 1:
@ -108,7 +107,7 @@ EventEmitter.prototype.emit = function emit(type) {
args[i - 1] = arguments[i]; args[i - 1] = arguments[i];
handler.apply(this, args); handler.apply(this, args);
} }
} else if (util.isObject(handler)) { } else if (handler !== null && typeof handler === 'object') {
len = arguments.length; len = arguments.length;
args = new Array(len - 1); args = new Array(len - 1);
for (i = 1; i < len; i++) for (i = 1; i < len; i++)
@ -129,7 +128,7 @@ EventEmitter.prototype.emit = function emit(type) {
EventEmitter.prototype.addListener = function addListener(type, listener) { EventEmitter.prototype.addListener = function addListener(type, listener) {
var m; var m;
if (!util.isFunction(listener)) if (typeof listener !== 'function')
throw TypeError('listener must be a function'); throw TypeError('listener must be a function');
if (!this._events) if (!this._events)
@ -139,13 +138,13 @@ EventEmitter.prototype.addListener = function addListener(type, listener) {
// adding it to the listeners, first emit "newListener". // adding it to the listeners, first emit "newListener".
if (this._events.newListener) if (this._events.newListener)
this.emit('newListener', type, this.emit('newListener', type,
util.isFunction(listener.listener) ? typeof listener.listener === 'function' ?
listener.listener : listener); listener.listener : listener);
if (!this._events[type]) if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object. // Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener; this._events[type] = listener;
else if (util.isObject(this._events[type])) else if (typeof this._events[type] === 'object')
// If we've already got an array, just append. // If we've already got an array, just append.
this._events[type].push(listener); this._events[type].push(listener);
else else
@ -153,7 +152,8 @@ EventEmitter.prototype.addListener = function addListener(type, listener) {
this._events[type] = [this._events[type], listener]; this._events[type] = [this._events[type], listener];
// Check for listener leak // Check for listener leak
if (util.isObject(this._events[type]) && !this._events[type].warned) { if (this._events[type] !== null && typeof this._events[type] === 'object' &&
!this._events[type].warned) {
var m = $getMaxListeners(this); var m = $getMaxListeners(this);
if (m && m > 0 && this._events[type].length > m) { if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true; this._events[type].warned = true;
@ -171,7 +171,7 @@ EventEmitter.prototype.addListener = function addListener(type, listener) {
EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function once(type, listener) { EventEmitter.prototype.once = function once(type, listener) {
if (!util.isFunction(listener)) if (typeof listener !== 'function')
throw TypeError('listener must be a function'); throw TypeError('listener must be a function');
var fired = false; var fired = false;
@ -196,7 +196,7 @@ EventEmitter.prototype.removeListener =
function removeListener(type, listener) { function removeListener(type, listener) {
var list, position, length, i; var list, position, length, i;
if (!util.isFunction(listener)) if (typeof listener !== 'function')
throw TypeError('listener must be a function'); throw TypeError('listener must be a function');
if (!this._events || !this._events[type]) if (!this._events || !this._events[type])
@ -207,12 +207,13 @@ EventEmitter.prototype.removeListener =
position = -1; position = -1;
if (list === listener || if (list === listener ||
(util.isFunction(list.listener) && list.listener === listener)) { (typeof list.listener === 'function' &&
list.listener === listener)) {
delete this._events[type]; delete this._events[type];
if (this._events.removeListener) if (this._events.removeListener)
this.emit('removeListener', type, listener); this.emit('removeListener', type, listener);
} else if (util.isObject(list)) { } else if (list !== null && typeof list === 'object') {
for (i = length; i-- > 0;) { for (i = length; i-- > 0;) {
if (list[i] === listener || if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) { (list[i].listener && list[i].listener === listener)) {
@ -267,7 +268,7 @@ EventEmitter.prototype.removeAllListeners =
listeners = this._events[type]; listeners = this._events[type];
if (util.isFunction(listeners)) { if (typeof listeners === 'function') {
this.removeListener(type, listeners); this.removeListener(type, listeners);
} else if (Array.isArray(listeners)) { } else if (Array.isArray(listeners)) {
// LIFO order // LIFO order
@ -283,7 +284,7 @@ EventEmitter.prototype.listeners = function listeners(type) {
var ret; var ret;
if (!this._events || !this._events[type]) if (!this._events || !this._events[type])
ret = []; ret = [];
else if (util.isFunction(this._events[type])) else if (typeof this._events[type] === 'function')
ret = [this._events[type]]; ret = [this._events[type]];
else else
ret = this._events[type].slice(); ret = this._events[type].slice();
@ -294,7 +295,7 @@ EventEmitter.listenerCount = function(emitter, type) {
var ret; var ret;
if (!emitter._events || !emitter._events[type]) if (!emitter._events || !emitter._events[type])
ret = 0; ret = 0;
else if (util.isFunction(emitter._events[type])) else if (typeof emitter._events[type] === 'function')
ret = 1; ret = 1;
else else
ret = emitter._events[type].length; ret = emitter._events[type].length;

142
lib/fs.js

@ -57,14 +57,14 @@ function rethrow() {
} }
function maybeCallback(cb) { function maybeCallback(cb) {
return util.isFunction(cb) ? cb : rethrow(); return typeof cb === 'function' ? cb : rethrow();
} }
// Ensure that callbacks run in the global context. Only use this function // Ensure that callbacks run in the global context. Only use this function
// for callbacks that are passed to the binding layer, callbacks that are // for callbacks that are passed to the binding layer, callbacks that are
// invoked from JS already run in the proper scope. // invoked from JS already run in the proper scope.
function makeCallback(cb) { function makeCallback(cb) {
if (!util.isFunction(cb)) { if (typeof cb !== 'function') {
return rethrow(); return rethrow();
} }
@ -218,11 +218,11 @@ fs.existsSync = function(path) {
fs.readFile = function(path, options, callback_) { fs.readFile = function(path, options, callback_) {
var callback = maybeCallback(arguments[arguments.length - 1]); var callback = maybeCallback(arguments[arguments.length - 1]);
if (util.isFunction(options) || !options) { if (!options || typeof options === 'function') {
options = { encoding: null, flag: 'r' }; options = { encoding: null, flag: 'r' };
} else if (util.isString(options)) { } else if (typeof options === 'string') {
options = { encoding: options, flag: 'r' }; options = { encoding: options, flag: 'r' };
} else if (!util.isObject(options)) { } else if (typeof options !== 'object') {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -317,9 +317,9 @@ fs.readFile = function(path, options, callback_) {
fs.readFileSync = function(path, options) { fs.readFileSync = function(path, options) {
if (!options) { if (!options) {
options = { encoding: null, flag: 'r' }; options = { encoding: null, flag: 'r' };
} else if (util.isString(options)) { } else if (typeof options === 'string') {
options = { encoding: options, flag: 'r' }; options = { encoding: options, flag: 'r' };
} else if (!util.isObject(options)) { } else if (typeof options !== 'object') {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -395,7 +395,7 @@ fs.readFileSync = function(path, options) {
// Used by binding.open and friends // Used by binding.open and friends
function stringToFlags(flag) { function stringToFlags(flag) {
// Only mess with strings // Only mess with strings
if (!util.isString(flag)) { if (typeof flag !== 'string') {
return flag; return flag;
} }
@ -448,9 +448,9 @@ fs.closeSync = function(fd) {
}; };
function modeNum(m, def) { function modeNum(m, def) {
if (util.isNumber(m)) if (typeof m === 'number')
return m; return m;
if (util.isString(m)) if (typeof m === 'string')
return parseInt(m, 8); return parseInt(m, 8);
if (def) if (def)
return modeNum(def); return modeNum(def);
@ -479,7 +479,7 @@ fs.openSync = function(path, flags, mode) {
}; };
fs.read = function(fd, buffer, offset, length, position, callback) { fs.read = function(fd, buffer, offset, length, position, callback) {
if (!util.isBuffer(buffer)) { if (!(buffer instanceof Buffer)) {
// legacy string interface (fd, length, position, encoding, callback) // legacy string interface (fd, length, position, encoding, callback)
var cb = arguments[4], var cb = arguments[4],
encoding = arguments[3]; encoding = arguments[3];
@ -513,7 +513,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) {
fs.readSync = function(fd, buffer, offset, length, position) { fs.readSync = function(fd, buffer, offset, length, position) {
var legacy = false; var legacy = false;
if (!util.isBuffer(buffer)) { if (!(buffer instanceof Buffer)) {
// legacy string interface (fd, length, position, encoding, callback) // legacy string interface (fd, length, position, encoding, callback)
legacy = true; legacy = true;
var encoding = arguments[3]; var encoding = arguments[3];
@ -551,9 +551,9 @@ fs.write = function(fd, buffer, offset, length, position, callback) {
callback(err, written || 0, buffer); callback(err, written || 0, buffer);
} }
if (util.isBuffer(buffer)) { if (buffer instanceof Buffer) {
// if no position is passed then assume null // if no position is passed then assume null
if (util.isFunction(position)) { if (typeof position === 'function') {
callback = position; callback = position;
position = null; position = null;
} }
@ -563,10 +563,10 @@ fs.write = function(fd, buffer, offset, length, position, callback) {
return binding.writeBuffer(fd, buffer, offset, length, position, req); return binding.writeBuffer(fd, buffer, offset, length, position, req);
} }
if (util.isString(buffer)) if (typeof buffer === 'string')
buffer += ''; buffer += '';
if (!util.isFunction(position)) { if (typeof position !== 'function') {
if (util.isFunction(offset)) { if (typeof offset === 'function') {
position = offset; position = offset;
offset = null; offset = null;
} else { } else {
@ -585,14 +585,14 @@ fs.write = function(fd, buffer, offset, length, position, callback) {
// OR // OR
// fs.writeSync(fd, string[, position[, encoding]]); // fs.writeSync(fd, string[, position[, encoding]]);
fs.writeSync = function(fd, buffer, offset, length, position) { fs.writeSync = function(fd, buffer, offset, length, position) {
if (util.isBuffer(buffer)) { if (buffer instanceof Buffer) {
if (util.isUndefined(position)) if (position === undefined)
position = null; position = null;
return binding.writeBuffer(fd, buffer, offset, length, position); return binding.writeBuffer(fd, buffer, offset, length, position);
} }
if (!util.isString(buffer)) if (typeof buffer !== 'string')
buffer += ''; buffer += '';
if (util.isUndefined(offset)) if (offset === undefined)
offset = null; offset = null;
return binding.writeString(fd, buffer, offset, length, position); return binding.writeString(fd, buffer, offset, length, position);
}; };
@ -616,15 +616,15 @@ fs.renameSync = function(oldPath, newPath) {
}; };
fs.truncate = function(path, len, callback) { fs.truncate = function(path, len, callback) {
if (util.isNumber(path)) { if (typeof path === 'number') {
var req = new FSReqWrap(); var req = new FSReqWrap();
req.oncomplete = callback; req.oncomplete = callback;
return fs.ftruncate(path, len, req); return fs.ftruncate(path, len, req);
} }
if (util.isFunction(len)) { if (typeof len === 'function') {
callback = len; callback = len;
len = 0; len = 0;
} else if (util.isUndefined(len)) { } else if (len === undefined) {
len = 0; len = 0;
} }
@ -642,11 +642,11 @@ fs.truncate = function(path, len, callback) {
}; };
fs.truncateSync = function(path, len) { fs.truncateSync = function(path, len) {
if (util.isNumber(path)) { if (typeof path === 'number') {
// legacy // legacy
return fs.ftruncateSync(path, len); return fs.ftruncateSync(path, len);
} }
if (util.isUndefined(len)) { if (len === undefined) {
len = 0; len = 0;
} }
// allow error to be thrown, but still close fd. // allow error to be thrown, but still close fd.
@ -660,10 +660,10 @@ fs.truncateSync = function(path, len) {
}; };
fs.ftruncate = function(fd, len, callback) { fs.ftruncate = function(fd, len, callback) {
if (util.isFunction(len)) { if (typeof len === 'function') {
callback = len; callback = len;
len = 0; len = 0;
} else if (util.isUndefined(len)) { } else if (len === undefined) {
len = 0; len = 0;
} }
var req = new FSReqWrap(); var req = new FSReqWrap();
@ -672,7 +672,7 @@ fs.ftruncate = function(fd, len, callback) {
}; };
fs.ftruncateSync = function(fd, len) { fs.ftruncateSync = function(fd, len) {
if (util.isUndefined(len)) { if (len === undefined) {
len = 0; len = 0;
} }
return binding.ftruncate(fd, len); return binding.ftruncate(fd, len);
@ -712,7 +712,7 @@ fs.fsyncSync = function(fd) {
}; };
fs.mkdir = function(path, mode, callback) { fs.mkdir = function(path, mode, callback) {
if (util.isFunction(mode)) callback = mode; if (typeof mode === 'function') callback = mode;
callback = makeCallback(callback); callback = makeCallback(callback);
if (!nullCheck(path, callback)) return; if (!nullCheck(path, callback)) return;
var req = new FSReqWrap(); var req = new FSReqWrap();
@ -806,7 +806,7 @@ function preprocessSymlinkDestination(path, type, linkPath) {
} }
fs.symlink = function(destination, path, type_, callback) { fs.symlink = function(destination, path, type_, callback) {
var type = (util.isString(type_) ? type_ : null); var type = (typeof type_ === 'string' ? type_ : null);
var callback = makeCallback(arguments[arguments.length - 1]); var callback = makeCallback(arguments[arguments.length - 1]);
if (!nullCheck(destination, callback)) return; if (!nullCheck(destination, callback)) return;
@ -822,7 +822,7 @@ fs.symlink = function(destination, path, type_, callback) {
}; };
fs.symlinkSync = function(destination, path, type) { fs.symlinkSync = function(destination, path, type) {
type = (util.isString(type) ? type : null); type = (typeof type === 'string' ? type : null);
nullCheck(destination); nullCheck(destination);
nullCheck(path); nullCheck(path);
@ -973,7 +973,7 @@ fs.chownSync = function(path, uid, gid) {
// converts Date or number to a fractional UNIX timestamp // converts Date or number to a fractional UNIX timestamp
function toUnixTimestamp(time) { function toUnixTimestamp(time) {
if (util.isNumber(time)) { if (typeof time === 'number') {
return time; return time;
} }
if (util.isDate(time)) { if (util.isDate(time)) {
@ -1043,11 +1043,11 @@ function writeAll(fd, buffer, offset, length, position, callback) {
fs.writeFile = function(path, data, options, callback) { fs.writeFile = function(path, data, options, callback) {
var callback = maybeCallback(arguments[arguments.length - 1]); var callback = maybeCallback(arguments[arguments.length - 1]);
if (util.isFunction(options) || !options) { if (!options || typeof options === 'function') {
options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; options = { encoding: 'utf8', mode: 0o666, flag: 'w' };
} else if (util.isString(options)) { } else if (typeof options === 'string') {
options = { encoding: options, mode: 0o666, flag: 'w' }; options = { encoding: options, mode: 0o666, flag: 'w' };
} else if (!util.isObject(options)) { } else if (typeof options !== 'object') {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -1058,7 +1058,7 @@ fs.writeFile = function(path, data, options, callback) {
if (openErr) { if (openErr) {
if (callback) callback(openErr); if (callback) callback(openErr);
} else { } else {
var buffer = util.isBuffer(data) ? data : new Buffer('' + data, var buffer = (data instanceof Buffer) ? data : new Buffer('' + data,
options.encoding || 'utf8'); options.encoding || 'utf8');
var position = /a/.test(flag) ? null : 0; var position = /a/.test(flag) ? null : 0;
writeAll(fd, buffer, 0, buffer.length, position, callback); writeAll(fd, buffer, 0, buffer.length, position, callback);
@ -1069,9 +1069,9 @@ fs.writeFile = function(path, data, options, callback) {
fs.writeFileSync = function(path, data, options) { fs.writeFileSync = function(path, data, options) {
if (!options) { if (!options) {
options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; options = { encoding: 'utf8', mode: 0o666, flag: 'w' };
} else if (util.isString(options)) { } else if (typeof options === 'string') {
options = { encoding: options, mode: 0o666, flag: 'w' }; options = { encoding: options, mode: 0o666, flag: 'w' };
} else if (!util.isObject(options)) { } else if (typeof options !== 'object') {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -1079,7 +1079,7 @@ fs.writeFileSync = function(path, data, options) {
var flag = options.flag || 'w'; var flag = options.flag || 'w';
var fd = fs.openSync(path, flag, options.mode); var fd = fs.openSync(path, flag, options.mode);
if (!util.isBuffer(data)) { if (!(data instanceof Buffer)) {
data = new Buffer('' + data, options.encoding || 'utf8'); data = new Buffer('' + data, options.encoding || 'utf8');
} }
var written = 0; var written = 0;
@ -1098,11 +1098,11 @@ fs.writeFileSync = function(path, data, options) {
fs.appendFile = function(path, data, options, callback_) { fs.appendFile = function(path, data, options, callback_) {
var callback = maybeCallback(arguments[arguments.length - 1]); var callback = maybeCallback(arguments[arguments.length - 1]);
if (util.isFunction(options) || !options) { if (!options || typeof options === 'function') {
options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; options = { encoding: 'utf8', mode: 0o666, flag: 'a' };
} else if (util.isString(options)) { } else if (typeof options === 'string') {
options = { encoding: options, mode: 0o666, flag: 'a' }; options = { encoding: options, mode: 0o666, flag: 'a' };
} else if (!util.isObject(options)) { } else if (typeof options !== 'object') {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -1114,9 +1114,9 @@ fs.appendFile = function(path, data, options, callback_) {
fs.appendFileSync = function(path, data, options) { fs.appendFileSync = function(path, data, options) {
if (!options) { if (!options) {
options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; options = { encoding: 'utf8', mode: 0o666, flag: 'a' };
} else if (util.isString(options)) { } else if (typeof options === 'string') {
options = { encoding: options, mode: 0o666, flag: 'a' }; options = { encoding: options, mode: 0o666, flag: 'a' };
} else if (!util.isObject(options)) { } else if (typeof options !== 'object') {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
if (!options.flag) if (!options.flag)
@ -1165,7 +1165,7 @@ fs.watch = function(filename) {
var options; var options;
var listener; var listener;
if (util.isObject(arguments[1])) { if (arguments[1] !== null && typeof arguments[1] === 'object') {
options = arguments[1]; options = arguments[1];
listener = arguments[2]; listener = arguments[2];
} else { } else {
@ -1173,8 +1173,8 @@ fs.watch = function(filename) {
listener = arguments[1]; listener = arguments[1];
} }
if (util.isUndefined(options.persistent)) options.persistent = true; if (options.persistent === undefined) options.persistent = true;
if (util.isUndefined(options.recursive)) options.recursive = false; if (options.recursive === undefined) options.recursive = false;
watcher = new FSWatcher(); watcher = new FSWatcher();
watcher.start(filename, options.persistent, options.recursive); watcher.start(filename, options.persistent, options.recursive);
@ -1247,7 +1247,7 @@ fs.watchFile = function(filename) {
persistent: true persistent: true
}; };
if (util.isObject(arguments[1])) { if (arguments[1] !== null && typeof arguments[1] === 'object') {
options = util._extend(options, arguments[1]); options = util._extend(options, arguments[1]);
listener = arguments[2]; listener = arguments[2];
} else { } else {
@ -1275,7 +1275,7 @@ fs.unwatchFile = function(filename, listener) {
var stat = statWatchers[filename]; var stat = statWatchers[filename];
if (util.isFunction(listener)) { if (typeof listener === 'function') {
stat.removeListener('change', listener); stat.removeListener('change', listener);
} else { } else {
stat.removeAllListeners('change'); stat.removeAllListeners('change');
@ -1378,7 +1378,7 @@ fs.realpathSync = function realpathSync(p, cache) {
linkTarget = seenLinks[id]; linkTarget = seenLinks[id];
} }
} }
if (util.isNull(linkTarget)) { if (linkTarget === null) {
fs.statSync(base); fs.statSync(base);
linkTarget = fs.readlinkSync(base); linkTarget = fs.readlinkSync(base);
} }
@ -1400,7 +1400,7 @@ fs.realpathSync = function realpathSync(p, cache) {
fs.realpath = function realpath(p, cache, cb) { fs.realpath = function realpath(p, cache, cb) {
if (!util.isFunction(cb)) { if (typeof cb !== 'function') {
cb = maybeCallback(cache); cb = maybeCallback(cache);
cache = null; cache = null;
} }
@ -1561,13 +1561,13 @@ function ReadStream(path, options) {
options.autoClose : true; options.autoClose : true;
this.pos = undefined; this.pos = undefined;
if (!util.isUndefined(this.start)) { if (this.start !== undefined) {
if (!util.isNumber(this.start)) { if (typeof this.start !== 'number') {
throw TypeError('start must be a Number'); throw TypeError('start must be a Number');
} }
if (util.isUndefined(this.end)) { if (this.end === undefined) {
this.end = Infinity; this.end = Infinity;
} else if (!util.isNumber(this.end)) { } else if (typeof this.end !== 'number') {
throw TypeError('end must be a Number'); throw TypeError('end must be a Number');
} }
@ -1578,7 +1578,7 @@ function ReadStream(path, options) {
this.pos = this.start; this.pos = this.start;
} }
if (!util.isNumber(this.fd)) if (typeof this.fd !== 'number')
this.open(); this.open();
this.on('end', function() { this.on('end', function() {
@ -1609,7 +1609,7 @@ ReadStream.prototype.open = function() {
}; };
ReadStream.prototype._read = function(n) { ReadStream.prototype._read = function(n) {
if (!util.isNumber(this.fd)) if (typeof this.fd !== 'number')
return this.once('open', function() { return this.once('open', function() {
this._read(n); this._read(n);
}); });
@ -1630,7 +1630,7 @@ ReadStream.prototype._read = function(n) {
var toRead = Math.min(pool.length - pool.used, n); var toRead = Math.min(pool.length - pool.used, n);
var start = pool.used; var start = pool.used;
if (!util.isUndefined(this.pos)) if (this.pos !== undefined)
toRead = Math.min(this.end - this.pos + 1, toRead); toRead = Math.min(this.end - this.pos + 1, toRead);
// already read everything we were supposed to read! // already read everything we were supposed to read!
@ -1643,7 +1643,7 @@ ReadStream.prototype._read = function(n) {
fs.read(this.fd, pool, pool.used, toRead, this.pos, onread); fs.read(this.fd, pool, pool.used, toRead, this.pos, onread);
// move the pool positions, and internal position for reading. // move the pool positions, and internal position for reading.
if (!util.isUndefined(this.pos)) if (this.pos !== undefined)
this.pos += toRead; this.pos += toRead;
pool.used += toRead; pool.used += toRead;
@ -1676,8 +1676,8 @@ ReadStream.prototype.close = function(cb) {
var self = this; var self = this;
if (cb) if (cb)
this.once('close', cb); this.once('close', cb);
if (this.closed || !util.isNumber(this.fd)) { if (this.closed || typeof this.fd !== 'number') {
if (!util.isNumber(this.fd)) { if (typeof this.fd !== 'number') {
this.once('open', close); this.once('open', close);
return; return;
} }
@ -1725,8 +1725,8 @@ function WriteStream(path, options) {
this.pos = undefined; this.pos = undefined;
this.bytesWritten = 0; this.bytesWritten = 0;
if (!util.isUndefined(this.start)) { if (this.start !== undefined) {
if (!util.isNumber(this.start)) { if (typeof this.start !== 'number') {
throw TypeError('start must be a Number'); throw TypeError('start must be a Number');
} }
if (this.start < 0) { if (this.start < 0) {
@ -1736,7 +1736,7 @@ function WriteStream(path, options) {
this.pos = this.start; this.pos = this.start;
} }
if (!util.isNumber(this.fd)) if (typeof this.fd !== 'number')
this.open(); this.open();
// dispose on finish. // dispose on finish.
@ -1761,10 +1761,10 @@ WriteStream.prototype.open = function() {
WriteStream.prototype._write = function(data, encoding, cb) { WriteStream.prototype._write = function(data, encoding, cb) {
if (!util.isBuffer(data)) if (!(data instanceof Buffer))
return this.emit('error', new Error('Invalid data')); return this.emit('error', new Error('Invalid data'));
if (!util.isNumber(this.fd)) if (typeof this.fd !== 'number')
return this.once('open', function() { return this.once('open', function() {
this._write(data, encoding, cb); this._write(data, encoding, cb);
}); });
@ -1779,7 +1779,7 @@ WriteStream.prototype._write = function(data, encoding, cb) {
cb(); cb();
}); });
if (!util.isUndefined(this.pos)) if (this.pos !== undefined)
this.pos += data.length; this.pos += data.length;
}; };
@ -1817,10 +1817,10 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) {
// parse arguments // parse arguments
if (arg1) { if (arg1) {
if (util.isString(arg1)) { if (typeof arg1 === 'string') {
encoding = arg1; encoding = arg1;
cb = arg2; cb = arg2;
} else if (util.isFunction(arg1)) { } else if (typeof arg1 === 'function') {
cb = arg1; cb = arg1;
} else { } else {
throw new Error('bad arg'); throw new Error('bad arg');
@ -1829,7 +1829,7 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) {
assertEncoding(encoding); assertEncoding(encoding);
// Change strings to buffers. SLOW // Change strings to buffers. SLOW
if (util.isString(data)) { if (typeof data === 'string') {
data = new Buffer(data, encoding); data = new Buffer(data, encoding);
} }

16
lib/https.js

@ -4,7 +4,7 @@ const tls = require('tls');
const url = require('url'); const url = require('url');
const http = require('http'); const http = require('http');
const util = require('util'); const util = require('util');
const inherits = require('util').inherits; const inherits = util.inherits;
const debug = util.debuglog('https'); const debug = util.debuglog('https');
function Server(opts, requestListener) { function Server(opts, requestListener) {
@ -41,21 +41,21 @@ exports.createServer = function(opts, requestListener) {
// HTTPS agents. // HTTPS agents.
function createConnection(port, host, options) { function createConnection(port, host, options) {
if (util.isObject(port)) { if (port !== null && typeof port === 'object') {
options = port; options = port;
} else if (util.isObject(host)) { } else if (host !== null && typeof host === 'object') {
options = host; options = host;
} else if (util.isObject(options)) { } else if (options !== null && typeof options === 'object') {
options = options; options = options;
} else { } else {
options = {}; options = {};
} }
if (util.isNumber(port)) { if (typeof port === 'number') {
options.port = port; options.port = port;
} }
if (util.isString(host)) { if (typeof host === 'string') {
options.host = host; options.host = host;
} }
@ -96,7 +96,7 @@ Agent.prototype.getName = function(options) {
name += options.pfx; name += options.pfx;
name += ':'; name += ':';
if (!util.isUndefined(options.rejectUnauthorized)) if (options.rejectUnauthorized !== undefined)
name += options.rejectUnauthorized; name += options.rejectUnauthorized;
return name; return name;
@ -108,7 +108,7 @@ exports.globalAgent = globalAgent;
exports.Agent = Agent; exports.Agent = Agent;
exports.request = function(options, cb) { exports.request = function(options, cb) {
if (util.isString(options)) { if (typeof options === 'string') {
options = url.parse(options); options = url.parse(options);
} else { } else {
options = util._extend({}, options); options = util._extend({}, options);

2
lib/module.js

@ -347,7 +347,7 @@ Module.prototype.load = function(filename) {
// `exports` property. // `exports` property.
Module.prototype.require = function(path) { Module.prototype.require = function(path) {
assert(path, 'missing path'); assert(path, 'missing path');
assert(util.isString(path), 'path must be a string'); assert(typeof path === 'string', 'path must be a string');
return Module._load(path, this); return Module._load(path, this);
}; };

66
lib/net.js

@ -45,7 +45,7 @@ function createHandle(fd) {
const debug = util.debuglog('net'); const debug = util.debuglog('net');
function isPipeName(s) { function isPipeName(s) {
return util.isString(s) && toNumber(s) === false; return typeof s === 'string' && toNumber(s) === false;
} }
exports.createServer = function() { exports.createServer = function() {
@ -77,7 +77,7 @@ exports.connect = exports.createConnection = function() {
function normalizeConnectArgs(args) { function normalizeConnectArgs(args) {
var options = {}; var options = {};
if (util.isObject(args[0])) { if (args[0] !== null && typeof args[0] === 'object') {
// connect(options, [cb]) // connect(options, [cb])
options = args[0]; options = args[0];
} else if (isPipeName(args[0])) { } else if (isPipeName(args[0])) {
@ -86,13 +86,13 @@ function normalizeConnectArgs(args) {
} else { } else {
// connect(port, [host], [cb]) // connect(port, [host], [cb])
options.port = args[0]; options.port = args[0];
if (util.isString(args[1])) { if (typeof args[1] === 'string') {
options.host = args[1]; options.host = args[1];
} }
} }
var cb = args[args.length - 1]; var cb = args[args.length - 1];
return util.isFunction(cb) ? [options, cb] : [options]; return typeof cb === 'function' ? [options, cb] : [options];
} }
exports._normalizeConnectArgs = normalizeConnectArgs; exports._normalizeConnectArgs = normalizeConnectArgs;
@ -122,16 +122,16 @@ function Socket(options) {
this._handle = null; this._handle = null;
this._host = null; this._host = null;
if (util.isNumber(options)) if (typeof options === 'number')
options = { fd: options }; // Legacy interface. options = { fd: options }; // Legacy interface.
else if (util.isUndefined(options)) else if (options === undefined)
options = {}; options = {};
stream.Duplex.call(this, options); stream.Duplex.call(this, options);
if (options.handle) { if (options.handle) {
this._handle = options.handle; // private this._handle = options.handle; // private
} else if (!util.isUndefined(options.fd)) { } else if (options.fd !== undefined) {
this._handle = createHandle(options.fd); this._handle = createHandle(options.fd);
this._handle.open(options.fd); this._handle.open(options.fd);
if ((options.fd == 1 || options.fd == 2) && if ((options.fd == 1 || options.fd == 2) &&
@ -261,7 +261,7 @@ function onSocketEnd() {
// of the other side sending a FIN. The standard 'write after end' // of the other side sending a FIN. The standard 'write after end'
// is overly vague, and makes it seem like the user's code is to blame. // is overly vague, and makes it seem like the user's code is to blame.
function writeAfterFIN(chunk, encoding, cb) { function writeAfterFIN(chunk, encoding, cb) {
if (util.isFunction(encoding)) { if (typeof encoding === 'function') {
cb = encoding; cb = encoding;
encoding = null; encoding = null;
} }
@ -271,7 +271,7 @@ function writeAfterFIN(chunk, encoding, cb) {
var self = this; var self = this;
// TODO: defer error events consistently everywhere, not just the cb // TODO: defer error events consistently everywhere, not just the cb
self.emit('error', er); self.emit('error', er);
if (util.isFunction(cb)) { if (typeof cb === 'function') {
process.nextTick(function() { process.nextTick(function() {
cb(er); cb(er);
}); });
@ -324,7 +324,7 @@ Socket.prototype._onTimeout = function() {
Socket.prototype.setNoDelay = function(enable) { Socket.prototype.setNoDelay = function(enable) {
// backwards compatibility: assume true when `enable` is omitted // backwards compatibility: assume true when `enable` is omitted
if (this._handle && this._handle.setNoDelay) if (this._handle && this._handle.setNoDelay)
this._handle.setNoDelay(util.isUndefined(enable) ? true : !!enable); this._handle.setNoDelay(enable === undefined ? true : !!enable);
}; };
@ -599,7 +599,7 @@ Socket.prototype.__defineGetter__('localPort', function() {
Socket.prototype.write = function(chunk, encoding, cb) { Socket.prototype.write = function(chunk, encoding, cb) {
if (!util.isString(chunk) && !util.isBuffer(chunk)) if (typeof chunk !== 'string' && !(chunk instanceof Buffer))
throw new TypeError('invalid data'); throw new TypeError('invalid data');
return stream.Duplex.prototype.write.apply(this, arguments); return stream.Duplex.prototype.write.apply(this, arguments);
}; };
@ -647,7 +647,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
if (err === 0) req._chunks = chunks; if (err === 0) req._chunks = chunks;
} else { } else {
var enc; var enc;
if (util.isBuffer(data)) { if (data instanceof Buffer) {
req.buffer = data; // Keep reference alive. req.buffer = data; // Keep reference alive.
enc = 'buffer'; enc = 'buffer';
} else { } else {
@ -713,14 +713,14 @@ Socket.prototype.__defineGetter__('bytesWritten', function() {
encoding = this._pendingEncoding; encoding = this._pendingEncoding;
state.getBuffer().forEach(function(el) { state.getBuffer().forEach(function(el) {
if (util.isBuffer(el.chunk)) if (el.chunk instanceof Buffer)
bytes += el.chunk.length; bytes += el.chunk.length;
else else
bytes += Buffer.byteLength(el.chunk, el.encoding); bytes += Buffer.byteLength(el.chunk, el.encoding);
}); });
if (data) { if (data) {
if (util.isBuffer(data)) if (data instanceof Buffer)
bytes += data.length; bytes += data.length;
else else
bytes += Buffer.byteLength(data, encoding); bytes += Buffer.byteLength(data, encoding);
@ -830,7 +830,7 @@ Socket.prototype.connect = function(options, cb) {
if (this.write !== Socket.prototype.write) if (this.write !== Socket.prototype.write)
this.write = Socket.prototype.write; this.write = Socket.prototype.write;
if (!util.isObject(options)) { if (options === null || typeof options !== 'object') {
// Old API: // Old API:
// connect(port, [host], [cb]) // connect(port, [host], [cb])
// connect(path, [cb]); // connect(path, [cb]);
@ -859,7 +859,7 @@ Socket.prototype.connect = function(options, cb) {
initSocketHandle(this); initSocketHandle(this);
} }
if (util.isFunction(cb)) { if (typeof cb === 'function') {
self.once('connect', cb); self.once('connect', cb);
} }
@ -885,7 +885,7 @@ Socket.prototype.connect = function(options, cb) {
if (localAddress && !exports.isIP(localAddress)) if (localAddress && !exports.isIP(localAddress))
throw new TypeError('localAddress must be a valid IP: ' + localAddress); throw new TypeError('localAddress must be a valid IP: ' + localAddress);
if (localPort && !util.isNumber(localPort)) if (localPort && typeof localPort !== 'number')
throw new TypeError('localPort should be a number: ' + localPort); throw new TypeError('localPort should be a number: ' + localPort);
if (port <= 0 || port > 65535) if (port <= 0 || port > 65535)
@ -998,13 +998,13 @@ function Server(/* [ options, ] listener */) {
var options; var options;
if (util.isFunction(arguments[0])) { if (typeof arguments[0] === 'function') {
options = {}; options = {};
self.on('connection', arguments[0]); self.on('connection', arguments[0]);
} else { } else {
options = arguments[0] || {}; options = arguments[0] || {};
if (util.isFunction(arguments[1])) { if (typeof arguments[1] === 'function') {
self.on('connection', arguments[1]); self.on('connection', arguments[1]);
} }
} }
@ -1052,7 +1052,7 @@ var createServerHandle = exports._createServerHandle =
var handle; var handle;
var isTCP = false; var isTCP = false;
if (util.isNumber(fd) && fd >= 0) { if (typeof fd === 'number' && fd >= 0) {
try { try {
handle = createHandle(fd); handle = createHandle(fd);
} }
@ -1117,10 +1117,10 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
var rval = null; var rval = null;
if (!address && !util.isNumber(fd)) { if (!address && typeof fd !== 'number') {
rval = createServerHandle('::', port, 6, fd); rval = createServerHandle('::', port, 6, fd);
if (util.isNumber(rval)) { if (typeof rval === 'number') {
rval = null; rval = null;
address = '0.0.0.0'; address = '0.0.0.0';
addressType = 4; addressType = 4;
@ -1133,7 +1133,7 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
if (rval === null) if (rval === null)
rval = createServerHandle(address, port, addressType, fd); rval = createServerHandle(address, port, addressType, fd);
if (util.isNumber(rval)) { if (typeof rval === 'number') {
var error = exceptionWithHostPort(rval, 'listen', address, port); var error = exceptionWithHostPort(rval, 'listen', address, port);
process.nextTick(function() { process.nextTick(function() {
self.emit('error', error); self.emit('error', error);
@ -1212,7 +1212,7 @@ Server.prototype.listen = function() {
var self = this; var self = this;
var lastArg = arguments[arguments.length - 1]; var lastArg = arguments[arguments.length - 1];
if (util.isFunction(lastArg)) { if (typeof lastArg === 'function') {
self.once('listening', lastArg); self.once('listening', lastArg);
} }
@ -1224,24 +1224,24 @@ Server.prototype.listen = function() {
const TCP = process.binding('tcp_wrap').TCP; const TCP = process.binding('tcp_wrap').TCP;
if (arguments.length === 0 || util.isFunction(arguments[0])) { if (arguments.length === 0 || typeof arguments[0] === 'function') {
// Bind to a random port. // Bind to a random port.
listen(self, null, 0, null, backlog); listen(self, null, 0, null, backlog);
} else if (util.isObject(arguments[0])) { } else if (arguments[0] !== null && typeof arguments[0] === 'object') {
var h = arguments[0]; var h = arguments[0];
h = h._handle || h.handle || h; h = h._handle || h.handle || h;
if (h instanceof TCP) { if (h instanceof TCP) {
self._handle = h; self._handle = h;
listen(self, null, -1, -1, backlog); listen(self, null, -1, -1, backlog);
} else if (util.isNumber(h.fd) && h.fd >= 0) { } else if (typeof h.fd === 'number' && h.fd >= 0) {
listen(self, null, null, null, backlog, h.fd); listen(self, null, null, null, backlog, h.fd);
} else { } else {
// The first argument is a configuration object // The first argument is a configuration object
if (h.backlog) if (h.backlog)
backlog = h.backlog; backlog = h.backlog;
if (util.isNumber(h.port)) { if (typeof h.port === 'number') {
if (h.host) if (h.host)
listenAfterLookup(h.port, h.host, backlog, h.exclusive); listenAfterLookup(h.port, h.host, backlog, h.exclusive);
else else
@ -1258,9 +1258,9 @@ Server.prototype.listen = function() {
var pipeName = self._pipeName = arguments[0]; var pipeName = self._pipeName = arguments[0];
listen(self, pipeName, -1, -1, backlog); listen(self, pipeName, -1, -1, backlog);
} else if (util.isUndefined(arguments[1]) || } else if (arguments[1] === undefined ||
util.isFunction(arguments[1]) || typeof arguments[1] === 'function' ||
util.isNumber(arguments[1])) { typeof arguments[1] === 'number') {
// The first argument is the port, no IP given. // The first argument is the port, no IP given.
listen(self, null, port, 4, backlog); listen(self, null, port, 4, backlog);
@ -1456,11 +1456,11 @@ if (process.platform === 'win32') {
var simultaneousAccepts; var simultaneousAccepts;
exports._setSimultaneousAccepts = function(handle) { exports._setSimultaneousAccepts = function(handle) {
if (util.isUndefined(handle)) { if (handle === undefined) {
return; return;
} }
if (util.isUndefined(simultaneousAccepts)) { if (simultaneousAccepts === undefined) {
simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS && simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS &&
process.env.NODE_MANY_ACCEPTS !== '0'); process.env.NODE_MANY_ACCEPTS !== '0');
} }

24
lib/path.js

@ -1,8 +1,6 @@
'use strict'; 'use strict';
const isWindows = process.platform === 'win32'; const isWindows = process.platform === 'win32';
const util = require('util');
// resolves . and .. elements in a path array with directory names there // resolves . and .. elements in a path array with directory names there
// must be no slashes or device names (c:\) in the array // must be no slashes or device names (c:\) in the array
@ -87,7 +85,7 @@ win32.resolve = function() {
} }
// Skip empty and invalid entries // Skip empty and invalid entries
if (!util.isString(path)) { if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings'); throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) { } else if (!path) {
continue; continue;
@ -176,7 +174,7 @@ win32.isAbsolute = function(path) {
win32.join = function() { win32.join = function() {
function f(p) { function f(p) {
if (!util.isString(p)) { if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings'); throw new TypeError('Arguments to path.join must be strings');
} }
return p; return p;
@ -265,7 +263,7 @@ win32.relative = function(from, to) {
win32._makeLong = function(path) { win32._makeLong = function(path) {
// Note: this will *probably* throw somewhere. // Note: this will *probably* throw somewhere.
if (!util.isString(path)) if (typeof path !== 'string')
return path; return path;
if (!path) { if (!path) {
@ -323,7 +321,7 @@ win32.extname = function(path) {
win32.format = function(pathObject) { win32.format = function(pathObject) {
if (!util.isObject(pathObject)) { if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError( throw new TypeError(
"Parameter 'pathObject' must be an object, not " + typeof pathObject "Parameter 'pathObject' must be an object, not " + typeof pathObject
); );
@ -331,7 +329,7 @@ win32.format = function(pathObject) {
var root = pathObject.root || ''; var root = pathObject.root || '';
if (!util.isString(root)) { if (typeof root !== 'string') {
throw new TypeError( throw new TypeError(
"'pathObject.root' must be a string or undefined, not " + "'pathObject.root' must be a string or undefined, not " +
typeof pathObject.root typeof pathObject.root
@ -353,7 +351,7 @@ win32.format = function(pathObject) {
win32.parse = function(pathString) { win32.parse = function(pathString) {
if (!util.isString(pathString)) { if (typeof pathString !== 'string') {
throw new TypeError( throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString "Parameter 'pathString' must be a string, not " + typeof pathString
); );
@ -398,7 +396,7 @@ posix.resolve = function() {
var path = (i >= 0) ? arguments[i] : process.cwd(); var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries // Skip empty and invalid entries
if (!util.isString(path)) { if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings'); throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) { } else if (!path) {
continue; continue;
@ -447,7 +445,7 @@ posix.join = function() {
var path = ''; var path = '';
for (var i = 0; i < arguments.length; i++) { for (var i = 0; i < arguments.length; i++) {
var segment = arguments[i]; var segment = arguments[i];
if (!util.isString(segment)) { if (typeof segment !== 'string') {
throw new TypeError('Arguments to path.join must be strings'); throw new TypeError('Arguments to path.join must be strings');
} }
if (segment) { if (segment) {
@ -546,7 +544,7 @@ posix.extname = function(path) {
posix.format = function(pathObject) { posix.format = function(pathObject) {
if (!util.isObject(pathObject)) { if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError( throw new TypeError(
"Parameter 'pathObject' must be an object, not " + typeof pathObject "Parameter 'pathObject' must be an object, not " + typeof pathObject
); );
@ -554,7 +552,7 @@ posix.format = function(pathObject) {
var root = pathObject.root || ''; var root = pathObject.root || '';
if (!util.isString(root)) { if (typeof root !== 'string') {
throw new TypeError( throw new TypeError(
"'pathObject.root' must be a string or undefined, not " + "'pathObject.root' must be a string or undefined, not " +
typeof pathObject.root typeof pathObject.root
@ -568,7 +566,7 @@ posix.format = function(pathObject) {
posix.parse = function(pathString) { posix.parse = function(pathString) {
if (!util.isString(pathString)) { if (typeof pathString !== 'string') {
throw new TypeError( throw new TypeError(
"Parameter 'pathString' must be a string, not " + typeof pathString "Parameter 'pathString' must be a string, not " + typeof pathString
); );

20
lib/querystring.js

@ -3,8 +3,6 @@
'use strict'; 'use strict';
const QueryString = exports; const QueryString = exports;
const util = require('util');
// 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.
@ -100,11 +98,13 @@ QueryString.escape = function(str) {
}; };
var stringifyPrimitive = function(v) { var stringifyPrimitive = function(v) {
if (util.isString(v)) let type = typeof v;
if (type === 'string')
return v; return v;
if (util.isBoolean(v)) if (type === 'boolean')
return v ? 'true' : 'false'; return v ? 'true' : 'false';
if (util.isNumber(v)) if (type === 'number')
return isFinite(v) ? v : ''; return isFinite(v) ? v : '';
return ''; return '';
}; };
@ -119,7 +119,7 @@ QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) {
encode = options.encodeURIComponent; encode = options.encodeURIComponent;
} }
if (util.isObject(obj)) { if (obj !== null && typeof obj === 'object') {
var keys = Object.keys(obj); var keys = Object.keys(obj);
var fields = []; var fields = [];
@ -128,7 +128,7 @@ QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) {
var v = obj[k]; var v = obj[k];
var ks = encode(stringifyPrimitive(k)) + eq; var ks = encode(stringifyPrimitive(k)) + eq;
if (util.isArray(v)) { if (Array.isArray(v)) {
for (var j = 0; j < v.length; j++) for (var j = 0; j < v.length; j++)
fields.push(ks + encode(stringifyPrimitive(v[j]))); fields.push(ks + encode(stringifyPrimitive(v[j])));
} else { } else {
@ -146,7 +146,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
eq = eq || '='; eq = eq || '=';
var obj = {}; var obj = {};
if (!util.isString(qs) || qs.length === 0) { if (typeof qs !== 'string' || qs.length === 0) {
return obj; return obj;
} }
@ -154,7 +154,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
qs = qs.split(sep); qs = qs.split(sep);
var maxKeys = 1000; var maxKeys = 1000;
if (options && util.isNumber(options.maxKeys)) { if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys; maxKeys = options.maxKeys;
} }
@ -192,7 +192,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
if (!hasOwnProperty(obj, k)) { if (!hasOwnProperty(obj, k)) {
obj[k] = v; obj[k] = v;
} else if (util.isArray(obj[k])) { } else if (Array.isArray(obj[k])) {
obj[k].push(v); obj[k].push(v);
} else { } else {
obj[k] = [obj[k], v]; obj[k] = [obj[k], v];

45
lib/readline.js

@ -43,13 +43,13 @@ function Interface(input, output, completer, terminal) {
completer = completer || function() { return []; }; completer = completer || function() { return []; };
if (!util.isFunction(completer)) { if (typeof completer !== 'function') {
throw new TypeError('Argument \'completer\' must be a function'); throw new TypeError('Argument \'completer\' must be a function');
} }
// backwards compat; check the isTTY prop of the output stream // backwards compat; check the isTTY prop of the output stream
// when `terminal` was not specified // when `terminal` was not specified
if (util.isUndefined(terminal) && !util.isNullOrUndefined(output)) { if (terminal === undefined && !(output === null || output === undefined)) {
terminal = !!output.isTTY; terminal = !!output.isTTY;
} }
@ -72,14 +72,15 @@ function Interface(input, output, completer, terminal) {
} }
function onend() { function onend() {
if (util.isString(self._line_buffer) && self._line_buffer.length > 0) { if (typeof self._line_buffer === 'string' &&
self._line_buffer.length > 0) {
self.emit('line', self._line_buffer); self.emit('line', self._line_buffer);
} }
self.close(); self.close();
} }
function ontermend() { function ontermend() {
if (util.isString(self.line) && self.line.length > 0) { if (typeof self.line === 'string' && self.line.length > 0) {
self.emit('line', self.line); self.emit('line', self.line);
} }
self.close(); self.close();
@ -123,13 +124,13 @@ function Interface(input, output, completer, terminal) {
this.history = []; this.history = [];
this.historyIndex = -1; this.historyIndex = -1;
if (!util.isNullOrUndefined(output)) if (output !== null && output !== undefined)
output.on('resize', onresize); output.on('resize', onresize);
self.once('close', function() { self.once('close', function() {
input.removeListener('keypress', onkeypress); input.removeListener('keypress', onkeypress);
input.removeListener('end', ontermend); input.removeListener('end', ontermend);
if (!util.isNullOrUndefined(output)) { if (output !== null && output !== undefined) {
output.removeListener('resize', onresize); output.removeListener('resize', onresize);
} }
}); });
@ -153,7 +154,7 @@ Interface.prototype.setPrompt = function(prompt) {
Interface.prototype._setRawMode = function(mode) { Interface.prototype._setRawMode = function(mode) {
if (util.isFunction(this.input.setRawMode)) { if (typeof this.input.setRawMode === 'function') {
return this.input.setRawMode(mode); return this.input.setRawMode(mode);
} }
}; };
@ -171,7 +172,7 @@ Interface.prototype.prompt = function(preserveCursor) {
Interface.prototype.question = function(query, cb) { Interface.prototype.question = function(query, cb) {
if (util.isFunction(cb)) { if (typeof cb === 'function') {
if (this._questionCallback) { if (this._questionCallback) {
this.prompt(); this.prompt();
} else { } else {
@ -196,10 +197,10 @@ Interface.prototype._onLine = function(line) {
}; };
Interface.prototype._writeToOutput = function _writeToOutput(stringToWrite) { Interface.prototype._writeToOutput = function _writeToOutput(stringToWrite) {
if (!util.isString(stringToWrite)) if (typeof stringToWrite !== 'string')
throw new TypeError('stringToWrite must be a string'); throw new TypeError('stringToWrite must be a string');
if (!util.isNullOrUndefined(this.output)) if (this.output !== null && this.output !== undefined)
this.output.write(stringToWrite); this.output.write(stringToWrite);
}; };
@ -296,7 +297,7 @@ Interface.prototype.write = function(d, key) {
// \r\n, \n, or \r followed by something other than \n // \r\n, \n, or \r followed by something other than \n
const lineEnding = /\r?\n|\r(?!\n)/; const lineEnding = /\r?\n|\r(?!\n)/;
Interface.prototype._normalWrite = function(b) { Interface.prototype._normalWrite = function(b) {
if (util.isUndefined(b)) { if (b === undefined) {
return; return;
} }
var string = this._decoder.write(b); var string = this._decoder.write(b);
@ -854,7 +855,7 @@ Interface.prototype._ttyWrite = function(s, key) {
break; break;
default: default:
if (util.isBuffer(s)) if (s instanceof Buffer)
s = s.toString('utf-8'); s = s.toString('utf-8');
if (s) { if (s) {
@ -952,8 +953,8 @@ const escapeCodeReAnywhere = new RegExp([
].join('|')); ].join('|'));
function emitKeys(stream, s) { function emitKeys(stream, s) {
if (util.isBuffer(s)) { if (s instanceof Buffer) {
if (s[0] > 127 && util.isUndefined(s[1])) { if (s[0] > 127 && s[1] === undefined) {
s[0] -= 128; s[0] -= 128;
s = '\x1b' + s.toString(stream.encoding || 'utf-8'); s = '\x1b' + s.toString(stream.encoding || 'utf-8');
} else { } else {
@ -1143,7 +1144,7 @@ function emitKeys(stream, s) {
} }
// Don't emit a key if no name was found // Don't emit a key if no name was found
if (util.isUndefined(key.name)) { if (key.name === undefined) {
key = undefined; key = undefined;
} }
@ -1163,16 +1164,16 @@ function emitKeys(stream, s) {
*/ */
function cursorTo(stream, x, y) { function cursorTo(stream, x, y) {
if (util.isNullOrUndefined(stream)) if (stream === null || stream === undefined)
return; return;
if (!util.isNumber(x) && !util.isNumber(y)) if (typeof x !== 'number' && typeof y !== 'number')
return; return;
if (!util.isNumber(x)) if (typeof x !== 'number')
throw new Error("Can't set cursor row without also setting it's column"); throw new Error("Can't set cursor row without also setting it's column");
if (!util.isNumber(y)) { if (typeof y !== 'number') {
stream.write('\x1b[' + (x + 1) + 'G'); stream.write('\x1b[' + (x + 1) + 'G');
} else { } else {
stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H');
@ -1186,7 +1187,7 @@ exports.cursorTo = cursorTo;
*/ */
function moveCursor(stream, dx, dy) { function moveCursor(stream, dx, dy) {
if (util.isNullOrUndefined(stream)) if (stream === null || stream === undefined)
return; return;
if (dx < 0) { if (dx < 0) {
@ -1212,7 +1213,7 @@ exports.moveCursor = moveCursor;
*/ */
function clearLine(stream, dir) { function clearLine(stream, dir) {
if (util.isNullOrUndefined(stream)) if (stream === null || stream === undefined)
return; return;
if (dir < 0) { if (dir < 0) {
@ -1234,7 +1235,7 @@ exports.clearLine = clearLine;
*/ */
function clearScreenDown(stream) { function clearScreenDown(stream) {
if (util.isNullOrUndefined(stream)) if (stream === null || stream === undefined)
return; return;
stream.write('\x1b[0J'); stream.write('\x1b[0J');

24
lib/repl.js

@ -63,7 +63,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
} }
var options, input, output, dom; var options, input, output, dom;
if (util.isObject(prompt)) { if (prompt !== null && typeof prompt === 'object') {
// an options object was given // an options object was given
options = prompt; options = prompt;
stream = options.stream || options.socket; stream = options.stream || options.socket;
@ -74,7 +74,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
ignoreUndefined = options.ignoreUndefined; ignoreUndefined = options.ignoreUndefined;
prompt = options.prompt; prompt = options.prompt;
dom = options.domain; dom = options.domain;
} else if (!util.isString(prompt)) { } else if (typeof prompt !== 'string') {
throw new Error('An options Object, or a prompt String are required'); throw new Error('An options Object, or a prompt String are required');
} else { } else {
options = {}; options = {};
@ -176,7 +176,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
options.terminal options.terminal
]); ]);
self.setPrompt(!util.isUndefined(prompt) ? prompt : '> '); self.setPrompt(prompt !== undefined ? prompt : '> ');
this.commands = {}; this.commands = {};
defineDefaultCommands(this); defineDefaultCommands(this);
@ -184,7 +184,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
// figure out which "writer" function to use // figure out which "writer" function to use
self.writer = options.writer || exports.writer; self.writer = options.writer || exports.writer;
if (util.isUndefined(options.useColors)) { if (options.useColors === undefined) {
options.useColors = self.terminal; options.useColors = self.terminal;
} }
self.useColors = !!options.useColors; self.useColors = !!options.useColors;
@ -303,7 +303,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
self.bufferedCommand = ''; self.bufferedCommand = '';
// If we got any output - print it (if no error) // If we got any output - print it (if no error)
if (!e && (!self.ignoreUndefined || !util.isUndefined(ret))) { if (!e && (!self.ignoreUndefined || ret !== undefined)) {
self.context._ = ret; self.context._ = ret;
self.outputStream.write(self.writer(ret) + '\n'); self.outputStream.write(self.writer(ret) + '\n');
} }
@ -431,7 +431,7 @@ const simpleExpressionRE =
// getter code. // getter code.
REPLServer.prototype.complete = function(line, callback) { REPLServer.prototype.complete = function(line, callback) {
// There may be local variables to evaluate, try a nested REPL // There may be local variables to evaluate, try a nested REPL
if (!util.isUndefined(this.bufferedCommand) && this.bufferedCommand.length) { if (this.bufferedCommand !== undefined && this.bufferedCommand.length) {
// Get a new array of inputed lines // Get a new array of inputed lines
var tmp = this.lines.slice(); var tmp = this.lines.slice();
// Kill off all function declarations to push all local variables into // Kill off all function declarations to push all local variables into
@ -573,7 +573,7 @@ REPLServer.prototype.complete = function(line, callback) {
this.eval('.scope', this.context, 'repl', function(err, globals) { this.eval('.scope', this.context, 'repl', function(err, globals) {
if (err || !globals) { if (err || !globals) {
addStandardGlobals(completionGroups, filter); addStandardGlobals(completionGroups, filter);
} else if (util.isArray(globals[0])) { } else if (Array.isArray(globals[0])) {
// Add grouped globals // Add grouped globals
globals.forEach(function(group) { globals.forEach(function(group) {
completionGroups.push(group); completionGroups.push(group);
@ -590,19 +590,19 @@ REPLServer.prototype.complete = function(line, callback) {
// if (e) console.log(e); // if (e) console.log(e);
if (obj != null) { if (obj != null) {
if (util.isObject(obj) || util.isFunction(obj)) { if (typeof obj === 'object' || typeof obj === 'function') {
memberGroups.push(Object.getOwnPropertyNames(obj)); memberGroups.push(Object.getOwnPropertyNames(obj));
} }
// works for non-objects // works for non-objects
try { try {
var sentinel = 5; var sentinel = 5;
var p; var p;
if (util.isObject(obj) || util.isFunction(obj)) { if (typeof obj === 'object' || typeof obj === 'function') {
p = Object.getPrototypeOf(obj); p = Object.getPrototypeOf(obj);
} else { } else {
p = obj.constructor ? obj.constructor.prototype : null; p = obj.constructor ? obj.constructor.prototype : null;
} }
while (!util.isNull(p)) { while (p !== null) {
memberGroups.push(Object.getOwnPropertyNames(p)); memberGroups.push(Object.getOwnPropertyNames(p));
p = Object.getPrototypeOf(p); p = Object.getPrototypeOf(p);
// Circular refs possible? Let's guard against that. // Circular refs possible? Let's guard against that.
@ -701,9 +701,9 @@ REPLServer.prototype.parseREPLKeyword = function(keyword, rest) {
REPLServer.prototype.defineCommand = function(keyword, cmd) { REPLServer.prototype.defineCommand = function(keyword, cmd) {
if (util.isFunction(cmd)) { if (typeof cmd === 'function') {
cmd = {action: cmd}; cmd = {action: cmd};
} else if (!util.isFunction(cmd.action)) { } else if (typeof cmd.action !== 'function') {
throw new Error('bad argument, action must be a function'); throw new Error('bad argument, action must be a function');
} }
this.commands[keyword] = cmd; this.commands[keyword] = cmd;

8
lib/smalloc.js

@ -40,10 +40,10 @@ Object.defineProperty(exports, 'Types', {
function alloc(n, obj, type) { function alloc(n, obj, type) {
n = n >>> 0; n = n >>> 0;
if (util.isUndefined(obj)) if (obj === undefined)
obj = {}; obj = {};
if (util.isNumber(obj)) { if (typeof obj === 'number') {
type = obj >>> 0; type = obj >>> 0;
obj = {}; obj = {};
} else if (util.isPrimitive(obj)) { } else if (util.isPrimitive(obj)) {
@ -53,7 +53,7 @@ function alloc(n, obj, type) {
// 1 == v8::kExternalUint8Array, 9 == v8::kExternalUint8ClampedArray // 1 == v8::kExternalUint8Array, 9 == v8::kExternalUint8ClampedArray
if (type < 1 || type > 9) if (type < 1 || type > 9)
throw new TypeError('unknown external array type: ' + type); throw new TypeError('unknown external array type: ' + type);
if (util.isArray(obj)) if (Array.isArray(obj))
throw new TypeError('Arrays are not supported'); throw new TypeError('Arrays are not supported');
if (n > kMaxLength) if (n > kMaxLength)
throw new RangeError('n > kMaxLength'); throw new RangeError('n > kMaxLength');
@ -65,7 +65,7 @@ function alloc(n, obj, type) {
function dispose(obj) { function dispose(obj) {
if (util.isPrimitive(obj)) if (util.isPrimitive(obj))
throw new TypeError('obj must be an Object'); throw new TypeError('obj must be an Object');
if (util.isBuffer(obj)) if (obj instanceof Buffer)
throw new TypeError('obj cannot be a Buffer'); throw new TypeError('obj cannot be a Buffer');
if (smalloc.isTypedArray(obj)) if (smalloc.isTypedArray(obj))
throw new TypeError('obj cannot be a typed array'); throw new TypeError('obj cannot be a typed array');

2
lib/stream.js

@ -65,7 +65,7 @@ Stream.prototype.pipe = function(dest, options) {
if (didOnEnd) return; if (didOnEnd) return;
didOnEnd = true; didOnEnd = true;
if (util.isFunction(dest.destroy)) dest.destroy(); if (typeof dest.destroy === 'function') dest.destroy();
} }
// don't leave dangling pipes when there are errors. // don't leave dangling pipes when there are errors.

8
lib/tls.js

@ -36,7 +36,7 @@ exports.getCiphers = function() {
// ("\x06spdy/2\x08http/1.1\x08http/1.0") // ("\x06spdy/2\x08http/1.1\x08http/1.0")
exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) {
// If NPNProtocols is Array - translate it into buffer // If NPNProtocols is Array - translate it into buffer
if (util.isArray(NPNProtocols)) { if (Array.isArray(NPNProtocols)) {
var buff = new Buffer(NPNProtocols.reduce(function(p, c) { var buff = new Buffer(NPNProtocols.reduce(function(p, c) {
return p + 1 + Buffer.byteLength(c); return p + 1 + Buffer.byteLength(c);
}, 0)); }, 0));
@ -53,7 +53,7 @@ exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) {
} }
// If it's already a Buffer - store it // If it's already a Buffer - store it
if (util.isBuffer(NPNProtocols)) { if (NPNProtocols instanceof Buffer) {
out.NPNProtocols = NPNProtocols; out.NPNProtocols = NPNProtocols;
} }
}; };
@ -160,7 +160,7 @@ exports.checkServerIdentity = function checkServerIdentity(host, cert) {
// RFC6125 // RFC6125
if (matchCN) { if (matchCN) {
var commonNames = cert.subject.CN; var commonNames = cert.subject.CN;
if (util.isArray(commonNames)) { if (Array.isArray(commonNames)) {
for (var i = 0, k = commonNames.length; i < k; ++i) { for (var i = 0, k = commonNames.length; i < k; ++i) {
dnsNames.push(regexpify(commonNames[i], true)); dnsNames.push(regexpify(commonNames[i], true));
} }
@ -208,7 +208,7 @@ exports.parseCertString = function parseCertString(s) {
var key = parts[i].slice(0, sepIndex); var key = parts[i].slice(0, sepIndex);
var value = parts[i].slice(sepIndex + 1); var value = parts[i].slice(sepIndex + 1);
if (key in out) { if (key in out) {
if (!util.isArray(out[key])) { if (!Array.isArray(out[key])) {
out[key] = [out[key]]; out[key] = [out[key]];
} }
out[key].push(value); out[key].push(value);

5
lib/tty.js

@ -1,11 +1,10 @@
'use strict'; 'use strict';
const inherits = require('util').inherits; const util = require('util');
const net = require('net'); const net = require('net');
const TTY = process.binding('tty_wrap').TTY; const TTY = process.binding('tty_wrap').TTY;
const isTTY = process.binding('tty_wrap').isTTY; const isTTY = process.binding('tty_wrap').isTTY;
const util = require('util'); const inherits = util.inherits;
const errnoException = util._errnoException; const errnoException = util._errnoException;

19
lib/url.js

@ -1,7 +1,6 @@
'use strict'; 'use strict';
const punycode = require('punycode'); const punycode = require('punycode');
const util = require('util');
exports.parse = urlParse; exports.parse = urlParse;
exports.resolve = urlResolve; exports.resolve = urlResolve;
@ -79,7 +78,7 @@ const slashedProtocol = {
const querystring = require('querystring'); const querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) { function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url; if (url instanceof Url) return url;
var u = new Url; var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost); u.parse(url, parseQueryString, slashesDenoteHost);
@ -87,7 +86,7 @@ function urlParse(url, parseQueryString, slashesDenoteHost) {
} }
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) { if (typeof url !== 'string') {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url); throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
} }
@ -353,7 +352,7 @@ function urlFormat(obj) {
// If it's an obj, this is a no-op. // If it's an obj, this is a no-op.
// this way, you can call url_format() on strings // this way, you can call url_format() on strings
// to clean up potentially wonky urls. // to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj); if (typeof obj === 'string') obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format(); return obj.format();
} }
@ -383,8 +382,8 @@ Url.prototype.format = function() {
} }
} }
if (this.query && if (this.query !== null &&
util.isObject(this.query) && typeof this.query === 'object' &&
Object.keys(this.query).length) { Object.keys(this.query).length) {
query = querystring.stringify(this.query); query = querystring.stringify(this.query);
} }
@ -428,7 +427,7 @@ function urlResolveObject(source, relative) {
} }
Url.prototype.resolveObject = function(relative) { Url.prototype.resolveObject = function(relative) {
if (util.isString(relative)) { if (typeof relative === 'string') {
var rel = new Url(); var rel = new Url();
rel.parse(relative, false, true); rel.parse(relative, false, true);
relative = rel; relative = rel;
@ -574,7 +573,7 @@ Url.prototype.resolveObject = function(relative) {
srcPath = srcPath.concat(relPath); srcPath = srcPath.concat(relPath);
result.search = relative.search; result.search = relative.search;
result.query = relative.query; result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) { } else if (relative.search !== null && relative.search !== undefined) {
// just pull out the search. // just pull out the search.
// like href='?foo'. // like href='?foo'.
// Put this after the other two cases because it simplifies the booleans // Put this after the other two cases because it simplifies the booleans
@ -593,7 +592,7 @@ Url.prototype.resolveObject = function(relative) {
result.search = relative.search; result.search = relative.search;
result.query = relative.query; result.query = relative.query;
//to support http.request //to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) { if (result.pathname !== null || result.search !== null) {
result.path = (result.pathname ? result.pathname : '') + result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : ''); (result.search ? result.search : '');
} }
@ -687,7 +686,7 @@ Url.prototype.resolveObject = function(relative) {
} }
//to support request.http //to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) { if (result.pathname !== null || result.search !== null) {
result.path = (result.pathname ? result.pathname : '') + result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : ''); (result.search ? result.search : '');
} }

88
lib/util.js

@ -2,7 +2,7 @@
const formatRegExp = /%[sdj%]/g; const formatRegExp = /%[sdj%]/g;
exports.format = function(f) { exports.format = function(f) {
if (!isString(f)) { if (typeof f !== 'string') {
var objects = []; var objects = [];
for (var i = 0; i < arguments.length; i++) { for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i])); objects.push(inspect(arguments[i]));
@ -30,7 +30,7 @@ exports.format = function(f) {
} }
}); });
for (var x = args[i]; i < len; x = args[++i]) { for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) { if (x === null || typeof x !== 'object') {
str += ' ' + x; str += ' ' + x;
} else { } else {
str += ' ' + inspect(x); str += ' ' + inspect(x);
@ -45,7 +45,7 @@ exports.format = function(f) {
// If --no-deprecation is set, then it is a no-op. // If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) { exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up. // Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) { if (global.process === undefined) {
return function() { return function() {
return exports.deprecate(fn, msg).apply(this, arguments); return exports.deprecate(fn, msg).apply(this, arguments);
}; };
@ -77,7 +77,7 @@ exports.deprecate = function(fn, msg) {
var debugs = {}; var debugs = {};
var debugEnviron; var debugEnviron;
exports.debuglog = function(set) { exports.debuglog = function(set) {
if (isUndefined(debugEnviron)) if (debugEnviron === undefined)
debugEnviron = process.env.NODE_DEBUG || ''; debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase(); set = set.toUpperCase();
if (!debugs[set]) { if (!debugs[set]) {
@ -112,7 +112,7 @@ function inspect(obj, opts) {
// legacy... // legacy...
if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3]; if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) { if (typeof opts === 'boolean') {
// legacy... // legacy...
ctx.showHidden = opts; ctx.showHidden = opts;
} else if (opts) { } else if (opts) {
@ -120,10 +120,10 @@ function inspect(obj, opts) {
exports._extend(ctx, opts); exports._extend(ctx, opts);
} }
// set default options // set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (ctx.showHidden === undefined) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2; if (ctx.depth === undefined) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false; if (ctx.colors === undefined) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.customInspect === undefined) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor; if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth); return formatValue(ctx, obj, ctx.depth);
} }
@ -195,13 +195,13 @@ function formatValue(ctx, value, recurseTimes) {
// Check that value is an object with an inspect function on it // Check that value is an object with an inspect function on it
if (ctx.customInspect && if (ctx.customInspect &&
value && value &&
isFunction(value.inspect) && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special // Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect && value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check. // Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) { !(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx); var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) { if (typeof ret !== 'string') {
ret = formatValue(ctx, ret, recurseTimes); ret = formatValue(ctx, ret, recurseTimes);
} }
return ret; return ret;
@ -236,7 +236,7 @@ function formatValue(ctx, value, recurseTimes) {
// ignore... // ignore...
} }
if (isString(raw)) { if (typeof raw === 'string') {
// for boxed Strings, we have to remove the 0-n indexed entries, // for boxed Strings, we have to remove the 0-n indexed entries,
// since they just noisey up the output and are redundant // since they just noisey up the output and are redundant
keys = keys.filter(function(key) { keys = keys.filter(function(key) {
@ -246,7 +246,7 @@ function formatValue(ctx, value, recurseTimes) {
// Some type of object without properties can be shortcutted. // Some type of object without properties can be shortcutted.
if (keys.length === 0) { if (keys.length === 0) {
if (isFunction(value)) { if (typeof value === 'function') {
var name = value.name ? ': ' + value.name : ''; var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special'); return ctx.stylize('[Function' + name + ']', 'special');
} }
@ -260,15 +260,15 @@ function formatValue(ctx, value, recurseTimes) {
return formatError(value); return formatError(value);
} }
// now check the `raw` value to handle boxed primitives // now check the `raw` value to handle boxed primitives
if (isString(raw)) { if (typeof raw === 'string') {
formatted = formatPrimitiveNoColor(ctx, raw); formatted = formatPrimitiveNoColor(ctx, raw);
return ctx.stylize('[String: ' + formatted + ']', 'string'); return ctx.stylize('[String: ' + formatted + ']', 'string');
} }
if (isNumber(raw)) { if (typeof raw === 'number') {
formatted = formatPrimitiveNoColor(ctx, raw); formatted = formatPrimitiveNoColor(ctx, raw);
return ctx.stylize('[Number: ' + formatted + ']', 'number'); return ctx.stylize('[Number: ' + formatted + ']', 'number');
} }
if (isBoolean(raw)) { if (typeof raw === 'boolean') {
formatted = formatPrimitiveNoColor(ctx, raw); formatted = formatPrimitiveNoColor(ctx, raw);
return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean'); return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
} }
@ -277,13 +277,13 @@ function formatValue(ctx, value, recurseTimes) {
var base = '', array = false, braces = ['{', '}']; var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array // Make Array say that they are Array
if (isArray(value)) { if (Array.isArray(value)) {
array = true; array = true;
braces = ['[', ']']; braces = ['[', ']'];
} }
// Make functions say that they are functions // Make functions say that they are functions
if (isFunction(value)) { if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : ''; var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']'; base = ' [Function' + n + ']';
} }
@ -304,19 +304,19 @@ function formatValue(ctx, value, recurseTimes) {
} }
// Make boxed primitive Strings look like such // Make boxed primitive Strings look like such
if (isString(raw)) { if (typeof raw === 'string') {
formatted = formatPrimitiveNoColor(ctx, raw); formatted = formatPrimitiveNoColor(ctx, raw);
base = ' ' + '[String: ' + formatted + ']'; base = ' ' + '[String: ' + formatted + ']';
} }
// Make boxed primitive Numbers look like such // Make boxed primitive Numbers look like such
if (isNumber(raw)) { if (typeof raw === 'number') {
formatted = formatPrimitiveNoColor(ctx, raw); formatted = formatPrimitiveNoColor(ctx, raw);
base = ' ' + '[Number: ' + formatted + ']'; base = ' ' + '[Number: ' + formatted + ']';
} }
// Make boxed primitive Booleans look like such // Make boxed primitive Booleans look like such
if (isBoolean(raw)) { if (typeof raw === 'boolean') {
formatted = formatPrimitiveNoColor(ctx, raw); formatted = formatPrimitiveNoColor(ctx, raw);
base = ' ' + '[Boolean: ' + formatted + ']'; base = ' ' + '[Boolean: ' + formatted + ']';
} }
@ -351,28 +351,32 @@ function formatValue(ctx, value, recurseTimes) {
function formatPrimitive(ctx, value) { function formatPrimitive(ctx, value) {
if (isUndefined(value)) if (value === undefined)
return ctx.stylize('undefined', 'undefined'); return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
// For some reason typeof null is "object", so special case here.
if (value === null)
return ctx.stylize('null', 'null');
var type = typeof value;
if (type === 'string') {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'") .replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\''; .replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string'); return ctx.stylize(simple, 'string');
} }
if (isNumber(value)) { if (type === 'number') {
// Format -0 as '-0'. Strict equality won't distinguish 0 from -0, // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
// so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
if (value === 0 && 1 / value < 0) if (value === 0 && 1 / value < 0)
return ctx.stylize('-0', 'number'); return ctx.stylize('-0', 'number');
return ctx.stylize('' + value, 'number'); return ctx.stylize('' + value, 'number');
} }
if (isBoolean(value)) if (type === 'boolean')
return ctx.stylize('' + value, 'boolean'); return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
// es6 symbol primitive // es6 symbol primitive
if (isSymbol(value)) if (type === 'symbol')
return ctx.stylize(value.toString(), 'symbol'); return ctx.stylize(value.toString(), 'symbol');
} }
@ -402,7 +406,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
} }
} }
keys.forEach(function(key) { keys.forEach(function(key) {
if (isSymbol(key) || !key.match(/^\d+$/)) { if (typeof key === 'symbol' || !key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true)); key, true));
} }
@ -426,7 +430,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
} }
} }
if (!hasOwnProperty(visibleKeys, key)) { if (!hasOwnProperty(visibleKeys, key)) {
if (isSymbol(key)) { if (typeof key === 'symbol') {
name = '[' + ctx.stylize(key.toString(), 'symbol') + ']'; name = '[' + ctx.stylize(key.toString(), 'symbol') + ']';
} else { } else {
name = '[' + key + ']'; name = '[' + key + ']';
@ -434,7 +438,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
} }
if (!str) { if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) { if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) { if (recurseTimes === null) {
str = formatValue(ctx, desc.value, null); str = formatValue(ctx, desc.value, null);
} else { } else {
str = formatValue(ctx, desc.value, recurseTimes - 1); str = formatValue(ctx, desc.value, recurseTimes - 1);
@ -454,7 +458,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
str = ctx.stylize('[Circular]', 'special'); str = ctx.stylize('[Circular]', 'special');
} }
} }
if (isUndefined(name)) { if (name === undefined) {
if (array && key.match(/^\d+$/)) { if (array && key.match(/^\d+$/)) {
return str; return str;
} }
@ -508,7 +512,7 @@ function isNull(arg) {
exports.isNull = isNull; exports.isNull = isNull;
function isNullOrUndefined(arg) { function isNullOrUndefined(arg) {
return arg == null; return arg === null || arg === undefined;
} }
exports.isNullOrUndefined = isNullOrUndefined; exports.isNullOrUndefined = isNullOrUndefined;
@ -528,27 +532,29 @@ function isSymbol(arg) {
exports.isSymbol = isSymbol; exports.isSymbol = isSymbol;
function isUndefined(arg) { function isUndefined(arg) {
return arg === void 0; return arg === undefined;
} }
exports.isUndefined = isUndefined; exports.isUndefined = isUndefined;
function isRegExp(re) { function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]'; return re !== null && typeof re === 'object' &&
objectToString(re) === '[object RegExp]';
} }
exports.isRegExp = isRegExp; exports.isRegExp = isRegExp;
function isObject(arg) { function isObject(arg) {
return typeof arg === 'object' && arg !== null; return arg !== null && typeof arg === 'object';
} }
exports.isObject = isObject; exports.isObject = isObject;
function isDate(d) { function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]'; return d !== null && typeof d === 'object' &&
objectToString(d) === '[object Date]';
} }
exports.isDate = isDate; exports.isDate = isDate;
function isError(e) { function isError(e) {
return isObject(e) && return e !== null && typeof e === 'object' &&
(objectToString(e) === '[object Error]' || e instanceof Error); (objectToString(e) === '[object Error]' || e instanceof Error);
} }
exports.isError = isError; exports.isError = isError;
@ -629,7 +635,7 @@ exports.inherits = function(ctor, superCtor) {
exports._extend = function(origin, add) { exports._extend = function(origin, add) {
// Don't do anything if add isn't an object // Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin; if (add === null || typeof add !== 'object') return origin;
var keys = Object.keys(add); var keys = Object.keys(add);
var i = keys.length; var i = keys.length;
@ -724,7 +730,7 @@ exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
var uv; var uv;
exports._errnoException = function(err, syscall, original) { exports._errnoException = function(err, syscall, original) {
if (isUndefined(uv)) uv = process.binding('uv'); if (uv === undefined) uv = process.binding('uv');
var errname = uv.errname(err); var errname = uv.errname(err);
var message = syscall + ' ' + errname; var message = syscall + ' ' + errname;
if (original) if (original)

3
lib/vm.js

@ -2,7 +2,6 @@
const binding = process.binding('contextify'); const binding = process.binding('contextify');
const Script = binding.ContextifyScript; const Script = binding.ContextifyScript;
const util = require('util');
// The binding provides a few useful primitives: // The binding provides a few useful primitives:
// - ContextifyScript(code, { filename = "evalmachine.anonymous", // - ContextifyScript(code, { filename = "evalmachine.anonymous",
@ -26,7 +25,7 @@ exports.createScript = function(code, options) {
}; };
exports.createContext = function(sandbox) { exports.createContext = function(sandbox) {
if (util.isUndefined(sandbox)) { if (sandbox === undefined) {
sandbox = {}; sandbox = {};
} else if (binding.isContext(sandbox)) { } else if (binding.isContext(sandbox)) {
return sandbox; return sandbox;

30
lib/zlib.js

@ -92,7 +92,7 @@ exports.createUnzip = function(o) {
// Convenience methods. // Convenience methods.
// compress/decompress a string or buffer in one step. // compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) { exports.deflate = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -104,7 +104,7 @@ exports.deflateSync = function(buffer, opts) {
}; };
exports.gzip = function(buffer, opts, callback) { exports.gzip = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -116,7 +116,7 @@ exports.gzipSync = function(buffer, opts) {
}; };
exports.deflateRaw = function(buffer, opts, callback) { exports.deflateRaw = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -128,7 +128,7 @@ exports.deflateRawSync = function(buffer, opts) {
}; };
exports.unzip = function(buffer, opts, callback) { exports.unzip = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -140,7 +140,7 @@ exports.unzipSync = function(buffer, opts) {
}; };
exports.inflate = function(buffer, opts, callback) { exports.inflate = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -152,7 +152,7 @@ exports.inflateSync = function(buffer, opts) {
}; };
exports.gunzip = function(buffer, opts, callback) { exports.gunzip = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -164,7 +164,7 @@ exports.gunzipSync = function(buffer, opts) {
}; };
exports.inflateRaw = function(buffer, opts, callback) { exports.inflateRaw = function(buffer, opts, callback) {
if (util.isFunction(opts)) { if (typeof opts === 'function') {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -209,9 +209,9 @@ function zlibBuffer(engine, buffer, callback) {
} }
function zlibBufferSync(engine, buffer) { function zlibBufferSync(engine, buffer) {
if (util.isString(buffer)) if (typeof buffer === 'string')
buffer = new Buffer(buffer); buffer = new Buffer(buffer);
if (!util.isBuffer(buffer)) if (!(buffer instanceof Buffer))
throw new TypeError('Not a string or buffer'); throw new TypeError('Not a string or buffer');
var flushFlag = binding.Z_FINISH; var flushFlag = binding.Z_FINISH;
@ -327,7 +327,7 @@ function Zlib(opts, mode) {
} }
if (opts.dictionary) { if (opts.dictionary) {
if (!util.isBuffer(opts.dictionary)) { if (!(opts.dictionary instanceof Buffer)) {
throw new Error('Invalid dictionary: it should be a Buffer instance'); throw new Error('Invalid dictionary: it should be a Buffer instance');
} }
} }
@ -349,10 +349,10 @@ function Zlib(opts, mode) {
}; };
var level = exports.Z_DEFAULT_COMPRESSION; var level = exports.Z_DEFAULT_COMPRESSION;
if (util.isNumber(opts.level)) level = opts.level; if (typeof opts.level === 'number') level = opts.level;
var strategy = exports.Z_DEFAULT_STRATEGY; var strategy = exports.Z_DEFAULT_STRATEGY;
if (util.isNumber(opts.strategy)) strategy = opts.strategy; if (typeof opts.strategy === 'number') strategy = opts.strategy;
this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
level, level,
@ -414,7 +414,7 @@ Zlib.prototype._flush = function(callback) {
Zlib.prototype.flush = function(kind, callback) { Zlib.prototype.flush = function(kind, callback) {
var ws = this._writableState; var ws = this._writableState;
if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) { if (typeof kind === 'function' || (kind === undefined && !callback)) {
callback = kind; callback = kind;
kind = binding.Z_FULL_FLUSH; kind = binding.Z_FULL_FLUSH;
} }
@ -459,7 +459,7 @@ Zlib.prototype._transform = function(chunk, encoding, cb) {
var ending = ws.ending || ws.ended; var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length); var last = ending && (!chunk || ws.length === chunk.length);
if (!util.isNull(chunk) && !util.isBuffer(chunk)) if (chunk !== null && !(chunk instanceof Buffer))
return cb(new Error('invalid input')); return cb(new Error('invalid input'));
if (this._closed) if (this._closed)
@ -490,7 +490,7 @@ Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
var self = this; var self = this;
var async = util.isFunction(cb); var async = typeof cb === 'function';
if (!async) { if (!async) {
var buffers = []; var buffers = [];

Loading…
Cancel
Save