diff --git a/lib/_debugger.js b/lib/_debugger.js index 0dc9c95c2c..955080ff2f 100644 --- a/lib/_debugger.js +++ b/lib/_debugger.js @@ -164,7 +164,8 @@ exports.Client = Client; Client.prototype._addHandle = function(desc) { - if (!util.isObject(desc) || !util.isNumber(desc.handle)) { + if (desc === null || typeof desc !== 'object' || + typeof desc.handle !== 'number') { return; } @@ -282,7 +283,7 @@ Client.prototype.reqLookup = function(refs, cb) { this.req(req, function(err, res) { if (err) return cb(err); for (var ref in res) { - if (util.isObject(res[ref])) { + if (res[ref] !== null && typeof res[ref] === 'object') { self._addHandle(res[ref]); } } @@ -544,8 +545,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) { mirrorValue = '[?]'; } - - if (util.isArray(mirror) && !util.isNumber(prop.name)) { + if (Array.isArray(mirror) && typeof prop.name !== 'number') { // Skip the 'length' property. return; } @@ -578,7 +578,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) { val = function() {}; } else if (handle.type === 'null') { val = null; - } else if (!util.isUndefined(handle.value)) { + } else if (handle.value !== undefined) { val = handle.value; } else if (handle.type === 'undefined') { val = undefined; @@ -879,7 +879,7 @@ Interface.prototype.print = function(text, oneline) { if (this.killed) return; 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) { this.stdout.write('\n'); @@ -1194,7 +1194,7 @@ Interface.prototype.scripts = function() { this.pause(); for (var id in client.scripts) { var script = client.scripts[id]; - if (util.isObject(script) && script.name) { + if (script !== null && typeof script === 'object' && script.name) { if (displayNatives || script.name == client.currentScript || !script.isNative) { @@ -1332,13 +1332,13 @@ Interface.prototype.setBreakpoint = function(script, line, ambiguous; // setBreakpoint() should insert breakpoint on current line - if (util.isUndefined(script)) { + if (script === undefined) { script = this.client.currentScript; line = this.client.currentSourceLine + 1; } // setBreakpoint(line-number) should insert breakpoint in current script - if (util.isUndefined(line) && util.isNumber(script)) { + if (line === undefined && typeof script === 'number') { line = script; script = this.client.currentScript; } @@ -1442,7 +1442,7 @@ Interface.prototype.clearBreakpoint = function(script, line) { if (bp.scriptId === script || bp.scriptReq === script || (bp.script && bp.script.indexOf(script) !== -1)) { - if (!util.isUndefined(index)) { + if (index !== undefined) { ambiguous = true; } scriptId = script; @@ -1470,11 +1470,11 @@ Interface.prototype.clearBreakpoint = function(script, line) { if (ambiguous) return this.error('Script name is ambiguous'); - if (util.isUndefined(scriptId)) { + if (scriptId === undefined) { return this.error('Script ' + script + ' not found'); } - if (util.isUndefined(breakpoint)) { + if (breakpoint === undefined) { return this.error('Breakpoint not found on line ' + line); } diff --git a/lib/_http_client.js b/lib/_http_client.js index 9212c0a1ba..6804157ee0 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -19,7 +19,7 @@ function ClientRequest(options, cb) { var self = this; OutgoingMessage.call(self); - if (util.isString(options)) { + if (typeof options === 'string') { options = url.parse(options); } @@ -27,7 +27,8 @@ function ClientRequest(options, cb) { var defaultAgent = options._defaultAgent || Agent.globalAgent; if (agent === false) { agent = new defaultAgent.constructor(); - } else if (util.isNullOrUndefined(agent) && !options.createConnection) { + } else if ((agent === null || agent === undefined) && + !options.createConnection) { agent = defaultAgent; } self.agent = agent; @@ -56,7 +57,7 @@ function ClientRequest(options, cb) { var port = options.port = options.port || defaultPort || 80; var host = options.host = options.hostname || options.host || 'localhost'; - if (util.isUndefined(options.setHost)) { + if (options.setHost === undefined) { var setHost = true; } @@ -68,7 +69,7 @@ function ClientRequest(options, cb) { self.once('response', cb); } - if (!util.isArray(options.headers)) { + if (!Array.isArray(options.headers)) { if (options.headers) { var keys = Object.keys(options.headers); for (var i = 0, l = keys.length; i < l; i++) { @@ -101,7 +102,7 @@ function ClientRequest(options, cb) { self.useChunkedEncodingByDefault = true; } - if (util.isArray(options.headers)) { + if (Array.isArray(options.headers)) { self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers); } else if (self.getHeader('expect')) { @@ -446,7 +447,7 @@ function tickOnSocket(req, socket) { httpSocketSetup(socket); // Propagate headers limit from request object to parser - if (util.isNumber(req.maxHeadersCount)) { + if (typeof req.maxHeadersCount === 'number') { parser.maxHeaderPairs = req.maxHeadersCount << 1; } else { // Set default value because parser may be reused from FreeList diff --git a/lib/_http_common.js b/lib/_http_common.js index 5f5c2d7fb2..209bd77bf4 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -8,7 +8,6 @@ const IncomingMessage = incoming.IncomingMessage; const readStart = incoming.readStart; const readStop = incoming.readStop; -const isNumber = require('util').isNumber; const debug = require('util').debuglog('http'); exports.debug = debug; @@ -69,7 +68,7 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, parser.incoming._addHeaderLines(headers, n); - if (isNumber(method)) { + if (typeof method === 'number') { // server only parser.incoming.method = HTTPParser.methods[method]; } else { diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index e35457ce5e..41ece371cd 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -130,7 +130,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { switch (field) { // Array headers: case 'set-cookie': - if (!util.isUndefined(dest[field])) { + if (dest[field] !== undefined) { dest[field].push(value); } else { dest[field] = [value]; @@ -152,13 +152,13 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { case 'location': case 'max-forwards': // drop duplicates - if (util.isUndefined(dest[field])) + if (dest[field] === undefined) dest[field] = value; break; default: // make comma-separated list - if (!util.isUndefined(dest[field])) + if (dest[field] !== undefined) dest[field] += ', ' + value; else { dest[field] = value; diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index a93b7e0683..25157d34a4 100644 --- a/lib/_http_outgoing.js +++ b/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 // this at a lower level and in a more general way. if (!this._headerSent) { - if (util.isString(data) && + if (typeof data === 'string' && encoding !== 'hex' && encoding !== 'base64') { data = this._header + data; @@ -122,13 +122,13 @@ OutgoingMessage.prototype._send = function(data, encoding, callback) { OutgoingMessage.prototype._writeRaw = function(data, encoding, callback) { - if (util.isFunction(encoding)) { + if (typeof encoding === 'function') { callback = encoding; encoding = null; } if (data.length === 0) { - if (util.isFunction(callback)) + if (typeof callback === 'function') process.nextTick(callback); return true; } @@ -187,7 +187,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { if (headers) { var keys = Object.keys(headers); - var isArray = util.isArray(headers); + var isArray = Array.isArray(headers); var field, value; for (var i = 0, l = keys.length; i < l; i++) { @@ -200,7 +200,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { value = headers[key]; } - if (util.isArray(value)) { + if (Array.isArray(value)) { for (var j = 0; j < value.length; j++) { storeHeader(this, state, field, value[j]); } @@ -408,7 +408,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) { 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'); } @@ -419,7 +419,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) { var len, ret; if (this.chunkedEncoding) { - if (util.isString(chunk) && + if (typeof chunk === 'string' && encoding !== 'hex' && encoding !== 'base64' && encoding !== 'binary') { @@ -428,7 +428,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) { ret = this._send(chunk, encoding, callback); } else { // buffer, or a non-toString-friendly encoding - if (util.isString(chunk)) + if (typeof chunk === 'string') len = Buffer.byteLength(chunk, encoding); else len = chunk.length; @@ -458,7 +458,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding, callback) { OutgoingMessage.prototype.addTrailers = function(headers) { this._trailer = ''; var keys = Object.keys(headers); - var isArray = util.isArray(headers); + var isArray = Array.isArray(headers); var field, value; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; @@ -479,15 +479,15 @@ const crlf_buf = new Buffer('\r\n'); OutgoingMessage.prototype.end = function(data, encoding, callback) { - if (util.isFunction(data)) { + if (typeof data === 'function') { callback = data; data = null; - } else if (util.isFunction(encoding)) { + } else if (typeof encoding === 'function') { callback = encoding; 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'); } @@ -500,10 +500,9 @@ OutgoingMessage.prototype.end = function(data, encoding, callback) { self.emit('finish'); } - if (util.isFunction(callback)) + if (typeof callback === 'function') this.once('finish', callback); - if (!this._header) { this._implicitHeader(); } diff --git a/lib/_http_server.js b/lib/_http_server.js index 20012a5ab1..d8b9799438 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -153,7 +153,7 @@ ServerResponse.prototype._implicitHeader = function() { ServerResponse.prototype.writeHead = function(statusCode, reason, obj) { var headers; - if (util.isString(reason)) { + if (typeof reason === 'string') { // writeHead(statusCode, reasonPhrase[, headers]) this.statusMessage = reason; } else { @@ -297,7 +297,7 @@ function connectionListener(socket) { parser.incoming = null; // Propagate headers limit from server instance to parser - if (util.isNumber(this.maxHeadersCount)) { + if (typeof this.maxHeadersCount === 'number') { parser.maxHeaderPairs = this.maxHeadersCount << 1; } else { // 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) && continueExpression.test(req.headers['expect'])) { res._expect_continue = true; diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index da16420828..2418648b69 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -95,7 +95,7 @@ function Readable(options) { Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; - if (util.isString(chunk) && !state.objectMode) { + if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = new Buffer(chunk, encoding); @@ -209,7 +209,7 @@ function howMuchToRead(n, state) { if (state.objectMode) return n === 0 ? 0 : 1; - if (util.isNull(n) || isNaN(n)) { + if (n === null || isNaN(n)) { // only flow one buffer at a time if (state.flowing && state.buffer.length) return state.buffer[0].length; @@ -245,7 +245,7 @@ Readable.prototype.read = function(n) { var state = this._readableState; var nOrig = n; - if (!util.isNumber(n) || n > 0) + if (typeof n !== 'number' || n > 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we @@ -333,7 +333,7 @@ Readable.prototype.read = function(n) { else ret = null; - if (util.isNull(ret)) { + if (ret === null) { state.needReadable = true; n = 0; } @@ -349,7 +349,7 @@ Readable.prototype.read = function(n) { if (nOrig !== n && state.ended && state.length === 0) endReadable(this); - if (!util.isNull(ret)) + if (ret !== null) this.emit('data', ret); return ret; @@ -357,9 +357,10 @@ Readable.prototype.read = function(n) { function chunkInvalid(state, chunk) { var er = null; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && + if (!(chunk instanceof Buffer) && + typeof chunk !== 'string' && + chunk !== null && + chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } @@ -757,7 +758,6 @@ Readable.prototype.wrap = function(stream) { chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) if (state.objectMode && (chunk === null || chunk === undefined)) return; else if (!state.objectMode && (!chunk || !chunk.length)) @@ -773,7 +773,7 @@ Readable.prototype.wrap = function(stream) { // proxy all the other methods. // important when wrapping filters and duplexes. 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() { return stream[method].apply(stream, arguments); }}(i); diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index f836208633..d3e7a13486 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -72,7 +72,7 @@ function afterTransform(stream, er, data) { ts.writechunk = null; ts.writecb = null; - if (!util.isNullOrUndefined(data)) + if (data !== null && data !== undefined) stream.push(data); if (cb) @@ -106,7 +106,7 @@ function Transform(options) { this._readableState.sync = false; this.once('prefinish', function() { - if (util.isFunction(this._flush)) + if (typeof this._flush === 'function') this._flush(function(er) { done(stream, er); }); @@ -154,7 +154,7 @@ Transform.prototype._write = function(chunk, encoding, cb) { Transform.prototype._read = function(n) { var ts = this._transformState; - if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index a3c65f4595..0176f4095f 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -162,9 +162,11 @@ function writeAfterEnd(stream, state, cb) { // how many bytes or characters. function validChunk(stream, state, chunk, cb) { var valid = true; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && + + if (!(chunk instanceof Buffer) && + typeof chunk !== 'string' && + chunk !== null && + chunk !== undefined && !state.objectMode) { var er = new TypeError('Invalid non-string/buffer chunk'); stream.emit('error', er); @@ -180,17 +182,17 @@ Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; var ret = false; - if (util.isFunction(encoding)) { + if (typeof encoding === 'function') { cb = encoding; encoding = null; } - if (util.isBuffer(chunk)) + if (chunk instanceof Buffer) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding; - if (!util.isFunction(cb)) + if (typeof cb !== 'function') cb = nop; if (state.ended) @@ -236,7 +238,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && - util.isString(chunk)) { + typeof chunk === 'string') { chunk = new Buffer(chunk, encoding); } 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. function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); - if (util.isBuffer(chunk)) + + if (chunk instanceof Buffer) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; @@ -418,16 +421,16 @@ Writable.prototype._writev = null; Writable.prototype.end = function(chunk, encoding, cb) { var state = this._writableState; - if (util.isFunction(chunk)) { + if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; - } else if (util.isFunction(encoding)) { + } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } - if (!util.isNullOrUndefined(chunk)) + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 3db0d6969f..2c15d91df8 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -1,6 +1,5 @@ 'use strict'; -const util = require('util'); const constants = require('constants'); 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 // cert's issuer in C++ code. if (options.ca) { - if (util.isArray(options.ca)) { + if (Array.isArray(options.ca)) { for (var i = 0, len = options.ca.length; i < len; i++) { c.context.addCACert(options.ca[i]); } @@ -95,7 +94,7 @@ exports.createSecureContext = function createSecureContext(options, context) { else c.context.setCiphers(tls.DEFAULT_CIPHERS); - if (util.isUndefined(options.ecdhCurve)) + if (options.ecdhCurve === undefined) c.context.setECDHCurve(tls.DEFAULT_ECDH_CURVE); else if (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.crl) { - if (util.isArray(options.crl)) { + if (Array.isArray(options.crl)) { for (var i = 0, len = options.crl.length; i < len; i++) { c.context.addCRL(options.crl[i]); } diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index f5be838d05..4148085503 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -36,7 +36,7 @@ SlabBuffer.prototype.use = function use(context, fn, size) { 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); if (bytes > 0) { @@ -72,7 +72,7 @@ function CryptoStream(pair, options) { this._finished = false; this._opposite = null; - if (util.isNull(slabBuffer)) slabBuffer = new SlabBuffer(); + if (slabBuffer === null) slabBuffer = new SlabBuffer(); this._buffer = slabBuffer; this.once('finish', onCryptoStreamFinish); @@ -142,7 +142,7 @@ CryptoStream.prototype.init = function init() { CryptoStream.prototype._write = function write(data, encoding, cb) { - assert(util.isNull(this._pending)); + assert(this._pending === null); // Black-hole data 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 if (this._opposite._halfRead) { - assert(util.isNull(this._sslOutCb)); + assert(this._sslOutCb === null); this._sslOutCb = cb; } else { cb(null); @@ -288,8 +288,8 @@ CryptoStream.prototype._read = function read(size) { } // Try writing pending data - if (!util.isNull(this._pending)) this._writePending(); - if (!util.isNull(this._opposite._pending)) this._opposite._writePending(); + if (this._pending !== null) this._writePending(); + if (this._opposite._pending !== null) this._opposite._writePending(); if (bytesRead === 0) { // 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 - if (!util.isNull(this._pending)) this._writePending(); + if (this._pending !== null) this._writePending(); this.writable = false; diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 6ce7c9f6ba..c6bf31b980 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -447,7 +447,7 @@ TLSSocket.prototype.setServername = function(name) { }; TLSSocket.prototype.setSession = function(session) { - if (util.isString(session)) + if (typeof session === 'string') session = new Buffer(session, 'binary'); this.ssl.setSession(session); }; @@ -554,10 +554,11 @@ TLSSocket.prototype.getCipher = function(err) { // function Server(/* [options], listener */) { var options, listener; - if (util.isObject(arguments[0])) { + + if (arguments[0] !== null && typeof arguments[0] === 'object') { options = arguments[0]; listener = arguments[1]; - } else if (util.isFunction(arguments[0])) { + } else if (typeof arguments[0] === 'function') { options = {}; listener = arguments[0]; } @@ -590,7 +591,7 @@ function Server(/* [options], listener */) { var timeout = options.handshakeTimeout || (120 * 1000); - if (!util.isNumber(timeout)) { + if (typeof timeout !== 'number') { throw new TypeError('handshakeTimeout must be a number'); } @@ -676,13 +677,13 @@ Server.prototype._setServerData = function(data) { Server.prototype.setOptions = function(options) { - if (util.isBoolean(options.requestCert)) { + if (typeof options.requestCert === 'boolean') { this.requestCert = options.requestCert; } else { this.requestCert = false; } - if (util.isBoolean(options.rejectUnauthorized)) { + if (typeof options.rejectUnauthorized === 'boolean') { this.rejectUnauthorized = options.rejectUnauthorized; } else { this.rejectUnauthorized = false; @@ -696,7 +697,7 @@ Server.prototype.setOptions = function(options) { if (options.secureProtocol) this.secureProtocol = options.secureProtocol; if (options.crl) this.crl = options.crl; if (options.ciphers) this.ciphers = options.ciphers; - if (!util.isUndefined(options.ecdhCurve)) + if (options.ecdhCurve !== undefined) this.ecdhCurve = options.ecdhCurve; if (options.dhparam) this.dhparam = options.dhparam; if (options.sessionTimeout) this.sessionTimeout = options.sessionTimeout; @@ -734,7 +735,7 @@ function SNICallback(servername, callback) { var ctx; this.server._contexts.some(function(elem) { - if (!util.isNull(servername.match(elem[0]))) { + if (servername.match(elem[0]) !== null) { ctx = elem[1]; return true; } @@ -763,9 +764,9 @@ function normalizeConnectArgs(listArgs) { var options = args[0]; var cb = args[1]; - if (util.isObject(listArgs[1])) { + if (listArgs[1] !== null && typeof listArgs[1] === 'object') { 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]); } diff --git a/lib/assert.js b/lib/assert.js index a13cc50316..5cd75b220a 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -59,7 +59,7 @@ assert.AssertionError = function AssertionError(options) { util.inherits(assert.AssertionError, Error); function truncate(s, n) { - if (util.isString(s)) { + if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; @@ -138,8 +138,7 @@ function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + } else if (actual instanceof Buffer && expected instanceof Buffer) { if (actual.length != expected.length) return false; 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', // 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; // 7.5 For all other Object pairs, including Array objects, equivalence is @@ -184,7 +184,7 @@ function isArguments(object) { } function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + if (a === null || a === undefined || b === null || b === undefined) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; @@ -270,11 +270,11 @@ function expectedException(actual, expected) { function _throws(shouldThrow, block, expected, message) { var actual; - if (!util.isFunction(block)) { + if (typeof block !== 'function') { throw new TypeError('block must be a function'); } - if (util.isString(expected)) { + if (typeof expected === 'string') { message = expected; expected = null; } diff --git a/lib/buffer.js b/lib/buffer.js index 41de85e673..19208b36ab 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -27,20 +27,20 @@ createPool(); function Buffer(subject, encoding) { - if (!util.isBuffer(this)) + if (!(this instanceof Buffer)) return new Buffer(subject, encoding); - if (util.isNumber(subject)) { + if (typeof subject === 'number') { this.length = +subject; - } else if (util.isString(subject)) { - if (!util.isString(encoding) || encoding.length === 0) + } else if (typeof subject === 'string') { + if (typeof encoding !== 'string' || encoding.length === 0) encoding = 'utf8'; this.length = Buffer.byteLength(subject, encoding); // Handle Arrays, Buffers, Uint8Arrays or JSON. - } else if (util.isObject(subject)) { - if (subject.type === 'Buffer' && util.isArray(subject.data)) + } else if (subject !== null && typeof subject === 'object') { + if (subject.type === 'Buffer' && Array.isArray(subject.data)) subject = subject.data; this.length = +subject.length; @@ -71,11 +71,11 @@ function Buffer(subject, encoding) { alloc(this, this.length); } - if (util.isNumber(subject)) { + if (typeof subject === 'number') { return; } - if (util.isString(subject)) { + if (typeof subject === 'string') { // 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 // the length to the actual length written. @@ -88,10 +88,10 @@ function Buffer(subject, encoding) { poolOffset -= (prevLen - len); } - } else if (util.isBuffer(subject)) { + } else if (subject instanceof Buffer) { 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 // way to access the data from the C++ API. for (var i = 0; i < this.length; i++) @@ -130,7 +130,7 @@ buffer.setupBufferJS(NativeBuffer, internal); // Static methods 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) { - if (!util.isArray(list)) + if (!Array.isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])'); - if (util.isUndefined(length)) { + if (length === undefined) { length = 0; for (var i = 0; i < list.length; i++) length += list[i].length; @@ -223,7 +223,7 @@ Buffer.prototype.toString = function(encoding, start, end) { var loweredCase = false; 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 (start < 0) start = 0; @@ -341,13 +341,13 @@ const writeMsg = '.write(string, encoding, offset, length) is deprecated.' + ' Use write(string[, offset[, length]][, encoding]) instead.'; Buffer.prototype.write = function(string, offset, length, encoding) { // Buffer#write(string); - if (util.isUndefined(offset)) { + if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) - } else if (util.isUndefined(length) && util.isString(offset)) { + } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; @@ -357,7 +357,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; - if (util.isUndefined(encoding)) + if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; @@ -383,7 +383,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) { } var remaining = this.length - offset; - if (util.isUndefined(length) || length > remaining) + if (length === undefined || length > remaining) length = remaining; encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; @@ -443,7 +443,7 @@ Buffer.prototype.toJSON = function() { Buffer.prototype.slice = function(start, end) { var len = this.length; start = ~~start; - end = util.isUndefined(end) ? len : ~~end; + end = end === undefined ? len : ~~end; if (start < 0) { start += len; @@ -468,7 +468,7 @@ Buffer.prototype.slice = function(start, end) { sliceOnto(this, buf, start, end); buf.length = end - start; if (buf.length > 0) - buf.parent = util.isUndefined(this.parent) ? this : this.parent; + buf.parent = this.parent === undefined ? this : this.parent; return buf; }; diff --git a/lib/child_process.js b/lib/child_process.js index 9226d127b3..a7587d0ac5 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -22,7 +22,7 @@ function handleWrapGetter(name, callback) { Object.defineProperty(handleWraps, name, { get: function() { - if (!util.isUndefined(cons)) return cons; + if (cons !== undefined) return cons; return cons = callback(); } }); @@ -295,9 +295,9 @@ function getSocketList(type, slave, key) { const INTERNAL_PREFIX = 'NODE_'; function handleMessage(target, message, handle) { var eventName = 'message'; - if (!util.isNull(message) && - util.isObject(message) && - util.isString(message.cmd) && + if (message !== null && + typeof message === 'object' && + typeof message.cmd === 'string' && message.cmd.length > INTERNAL_PREFIX.length && message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) { eventName = 'internalMessage'; @@ -353,7 +353,7 @@ function setupChannel(target, channel) { target.on('internalMessage', function(message, handle) { // Once acknowledged - continue sending handles. if (message.cmd === 'NODE_HANDLE_ACK') { - assert(util.isArray(target._handleQueue)); + assert(Array.isArray(target._handleQueue)); var queue = target._handleQueue; target._handleQueue = null; @@ -400,7 +400,7 @@ function setupChannel(target, channel) { target._send = function(message, handle, swallowErrors) { assert(this.connected || this._channel); - if (util.isUndefined(message)) + if (message === undefined) throw new TypeError('message cannot be undefined'); // package messages with a handle object @@ -538,7 +538,7 @@ exports.fork = function(modulePath /*, args, options*/) { // Get options and args arguments. var options, args, execArgv; - if (util.isArray(arguments[1])) { + if (Array.isArray(arguments[1])) { args = arguments[1]; options = util._extend({}, arguments[2]); } else { @@ -583,7 +583,7 @@ exports._forkChild = function(fd) { function normalizeExecArgs(command /*, options, callback */) { var file, args, options, callback; - if (util.isFunction(arguments[1])) { + if (typeof arguments[1] === 'function') { options = undefined; callback = arguments[1]; } else { @@ -638,11 +638,11 @@ exports.execFile = function(file /* args, options, callback */) { // Parse the parameters. - if (util.isFunction(arguments[arguments.length - 1])) { + if (typeof arguments[arguments.length - 1] === 'function') { callback = arguments[arguments.length - 1]; } - if (util.isArray(arguments[1])) { + if (Array.isArray(arguments[1])) { args = arguments[1]; options = util._extend(options, arguments[2]); } else { @@ -806,14 +806,14 @@ function _validateStdio(stdio, sync) { ipcFd; // Replace shortcut with an array - if (util.isString(stdio)) { + if (typeof stdio === 'string') { switch (stdio) { case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break; case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'inherit': stdio = [0, 1, 2]; break; 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: ' + util.inspect(stdio)); } @@ -837,13 +837,13 @@ function _validateStdio(stdio, sync) { } // Defaults - if (util.isNullOrUndefined(stdio)) { + if (stdio === null || stdio === undefined) { stdio = i < 3 ? 'pipe' : 'ignore'; } if (stdio === null || stdio === '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 = { type: 'pipe', readable: i === 0, @@ -855,7 +855,7 @@ function _validateStdio(stdio, sync) { acc.push(a); } else if (stdio === 'ipc') { - if (sync || !util.isUndefined(ipc)) { + if (sync || ipc !== undefined) { // Cleanup previously created pipes cleanup(); if (!sync) @@ -877,7 +877,7 @@ function _validateStdio(stdio, sync) { type: 'inherit', fd: i }); - } else if (util.isNumber(stdio) || util.isNumber(stdio.fd)) { + } else if (typeof stdio === 'number' || typeof stdio.fd === 'number') { acc.push({ type: 'fd', fd: stdio.fd || stdio @@ -893,7 +893,7 @@ function _validateStdio(stdio, sync) { wrapType: getHandleWrapType(handle), handle: handle }); - } else if (util.isBuffer(stdio) || util.isString(stdio)) { + } else if (stdio instanceof Buffer || typeof stdio === 'string') { if (!sync) { cleanup(); throw new TypeError('Asynchronous forks do not support Buffer input: ' + @@ -919,7 +919,8 @@ function normalizeSpawnArguments(file /*, args, options*/) { if (Array.isArray(arguments[1])) { args = arguments[1].slice(0); 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'); } else { args = []; @@ -928,7 +929,7 @@ function normalizeSpawnArguments(file /*, args, options*/) { if (options === undefined) options = {}; - else if (!util.isObject(options)) + else if (options === null || typeof options !== 'object') throw new TypeError('options argument must be an object'); options = util._extend({}, options); @@ -1089,7 +1090,7 @@ ChildProcess.prototype.spawn = function(options) { ipcFd = stdio.ipcFd; stdio = options.stdio = stdio.stdio; - if (!util.isUndefined(ipc)) { + if (ipc !== undefined) { // Let child process know about opened IPC channel options.envPairs = options.envPairs || []; 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; - this.stdout = stdio.length >= 2 && !util.isUndefined(stdio[1].socket) ? + this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ? 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; 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 - if (!util.isUndefined(ipc)) setupChannel(this, ipc); + if (ipc !== undefined) setupChannel(this, ipc); return err; }; @@ -1183,7 +1184,7 @@ ChildProcess.prototype.kill = function(sig) { signal = constants[sig]; } - if (util.isUndefined(signal)) { + if (signal === undefined) { 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]); if (Buffer.isBuffer(input)) pipe.input = input; - else if (util.isString(input)) + else if (typeof input === 'string') pipe.input = new Buffer(input, options.encoding); else throw new TypeError(util.format( diff --git a/lib/cluster.js b/lib/cluster.js index 9312fc28f2..14d0bc69b3 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -22,7 +22,7 @@ function Worker(options) { EventEmitter.call(this); - if (!util.isObject(options)) + if (options === null || typeof options !== 'object') options = {}; this.suicide = undefined; @@ -68,7 +68,7 @@ function SharedHandle(key, address, port, addressType, backlog, fd) { else rval = net._createServerHandle(address, port, addressType, fd); - if (util.isNumber(rval)) + if (typeof rval === 'number') this.errno = rval; else this.handle = rval; @@ -135,7 +135,7 @@ RoundRobinHandle.prototype.add = function(worker, send) { 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. this.server.once('listening', done); this.server.once('error', function(err) { @@ -170,7 +170,7 @@ RoundRobinHandle.prototype.handoff = function(worker) { return; // Worker is closing (or has closed) the server. } var handle = this.handles.shift(); - if (util.isUndefined(handle)) { + if (handle === undefined) { this.free.push(worker); // Add to ready queue again. return; } @@ -203,7 +203,7 @@ function masterInit() { 'rr': SCHED_RR }[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 // way IOCP is wired up. Bert is going to fix that, eventually. schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; @@ -438,7 +438,7 @@ function masterInit() { message.fd]; var key = args.join(':'); var handle = handles[key]; - if (util.isUndefined(handle)) { + if (handle === undefined) { var constructor = RoundRobinHandle; // UDP is exempt from round-robin connection balancing for what should // be obvious reasons: it's connectionless. There is nothing to send to @@ -562,7 +562,7 @@ function workerInit() { delete handles[key]; return close.apply(this, arguments); }; - assert(util.isUndefined(handles[key])); + assert(handles[key] === undefined); handles[key] = handle; cb(message.errno, handle); } @@ -586,7 +586,7 @@ function workerInit() { // the ack by the master process in which we can still receive handles. // onconnection() below handles that by sending those handles back to // the master. - if (util.isUndefined(key)) return; + if (key === undefined) return; send({ act: 'close', key: key }); delete handles[key]; key = undefined; @@ -607,7 +607,7 @@ function workerInit() { if (message.sockname) { handle.getsockname = getsockname; // TCP handles only. } - assert(util.isUndefined(handles[key])); + assert(handles[key] === undefined); handles[key] = handle; cb(0, handle); } @@ -616,7 +616,7 @@ function workerInit() { function onconnection(message, handle) { var key = message.key; var server = handles[key]; - var accepted = !util.isUndefined(server); + var accepted = server !== undefined; send({ ack: message.seq, accepted: accepted }); if (accepted) server.onconnection(0, handle); } @@ -664,7 +664,7 @@ function internal(worker, cb) { return function(message, handle) { if (message.cmd !== 'NODE_CLUSTER') return; var fn = cb; - if (!util.isUndefined(message.ack)) { + if (message.ack !== undefined) { fn = callbacks[message.ack]; delete callbacks[message.ack]; } diff --git a/lib/console.js b/lib/console.js index 323d23374a..63e3c5e0bf 100644 --- a/lib/console.js +++ b/lib/console.js @@ -6,7 +6,7 @@ function Console(stdout, stderr) { if (!(this instanceof Console)) { 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'); } if (!stderr) { diff --git a/lib/crypto.js b/lib/crypto.js index f8efffda48..42564c79e4 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -25,7 +25,7 @@ const DH_GENERATOR = 2; // to break them unnecessarily. function toBuf(str, encoding) { encoding = encoding || 'binary'; - if (util.isString(str)) { + if (typeof str === 'string') { if (encoding === 'buffer') encoding = 'binary'; str = new Buffer(str, encoding); @@ -92,7 +92,7 @@ Hash.prototype._flush = function(callback) { Hash.prototype.update = function(data, encoding) { encoding = encoding || exports.DEFAULT_ENCODING; - if (encoding === 'buffer' && util.isString(data)) + if (encoding === 'buffer' && typeof data === 'string') encoding = 'binary'; this._handle.update(data, encoding); return this; @@ -369,7 +369,7 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) { if (!(this instanceof DiffieHellman)) return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding); - if (!util.isBuffer(sizeOrKey) && + if (!(sizeOrKey instanceof Buffer) && typeof sizeOrKey !== 'number' && typeof sizeOrKey !== 'string') throw new TypeError('First argument should be number, string or Buffer'); @@ -513,7 +513,7 @@ DiffieHellman.prototype.setPrivateKey = function(key, encoding) { function ECDH(curve) { - if (!util.isString(curve)) + if (typeof curve !== 'string') throw new TypeError('curve should be a string'); this._handle = new binding.ECDH(curve); @@ -566,12 +566,12 @@ exports.pbkdf2 = function(password, keylen, digest, callback) { - if (util.isFunction(digest)) { + if (typeof digest === 'function') { callback = digest; digest = undefined; } - if (!util.isFunction(callback)) + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2'); return pbkdf2(password, salt, iterations, keylen, digest, callback); @@ -632,10 +632,10 @@ Certificate.prototype.exportChallenge = function(object, encoding) { exports.setEngine = function setEngine(id, flags) { - if (!util.isString(id)) + if (typeof id !== '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'); flags = flags >>> 0; diff --git a/lib/dgram.js b/lib/dgram.js index 19cf1c4ea0..a919e16497 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -61,7 +61,7 @@ function newHandle(type) { exports._createSocketHandle = function(address, port, addressType, fd) { // 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); @@ -97,7 +97,7 @@ function Socket(type, listener) { // If true - UV_UDP_REUSEADDR flag will be set this._reuseAddr = options && options.reuseAddr; - if (util.isFunction(listener)) + if (typeof listener === 'function') this.on('message', listener); } util.inherits(Socket, events.EventEmitter); @@ -143,7 +143,7 @@ Socket.prototype.bind = function(port /*, address, callback*/) { 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]); const UDP = process.binding('udp_wrap').UDP; @@ -156,12 +156,12 @@ Socket.prototype.bind = function(port /*, address, callback*/) { var address; var exclusive; - if (util.isObject(port)) { + if (port !== null && typeof port === 'object') { address = port.address || ''; exclusive = !!port.exclusive; port = port.port; } else { - address = util.isFunction(arguments[1]) ? '' : arguments[1]; + address = typeof arguments[1] === 'function' ? '' : arguments[1]; exclusive = false; } @@ -225,10 +225,10 @@ Socket.prototype.sendto = function(buffer, port, address, 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'); - if (!util.isString(address)) + if (typeof address !== 'string') throw new Error(this.type + ' sockets must send to port, address'); this.send(buffer, offset, length, port, address, callback); @@ -243,10 +243,10 @@ Socket.prototype.send = function(buffer, callback) { var self = this; - if (util.isString(buffer)) + if (typeof buffer === 'string') buffer = new Buffer(buffer); - if (!util.isBuffer(buffer)) + if (!(buffer instanceof Buffer)) throw new TypeError('First argument must be a buffer or string.'); 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 // else. - if (!util.isFunction(callback)) + if (typeof callback !== 'function') callback = undefined; self._healthCheck(); @@ -378,7 +378,7 @@ Socket.prototype.setBroadcast = function(arg) { Socket.prototype.setTTL = function(arg) { - if (!util.isNumber(arg)) { + if (typeof arg !== 'number') { throw new TypeError('Argument must be a number'); } @@ -392,7 +392,7 @@ Socket.prototype.setTTL = function(arg) { Socket.prototype.setMulticastTTL = function(arg) { - if (!util.isNumber(arg)) { + if (typeof arg !== 'number') { throw new TypeError('Argument must be a number'); } diff --git a/lib/dns.js b/lib/dns.js index 8cfa7f58c5..e084fb5e5d 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -53,7 +53,7 @@ function errnoException(err, syscall, hostname) { // callback.immediately = true; // } function makeAsync(callback) { - if (!util.isFunction(callback)) { + if (typeof callback !== 'function') { return callback; } return function asyncCallback() { @@ -96,7 +96,7 @@ exports.lookup = function lookup(hostname, options, callback) { family = 0; } else if (typeof callback !== 'function') { throw TypeError('invalid arguments: callback must be passed'); - } else if (util.isObject(options)) { + } else if (options !== null && typeof options === 'object') { hints = options.hints >>> 0; family = options.family >>> 0; @@ -192,9 +192,9 @@ function resolver(bindingName) { var binding = cares[bindingName]; return function query(name, callback) { - if (!util.isString(name)) { + if (typeof name !== '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'); } @@ -228,17 +228,17 @@ exports.reverse = resolveMap.PTR = resolver('getHostByAddr'); exports.resolve = function(hostname, type_, callback_) { var resolver, callback; - if (util.isString(type_)) { + if (typeof type_ === 'string') { resolver = resolveMap[type_]; callback = callback_; - } else if (util.isFunction(type_)) { + } else if (typeof type_ === 'function') { resolver = exports.resolve4; callback = type_; } else { throw new Error('Type must be a string'); } - if (util.isFunction(resolver)) { + if (typeof resolver === 'function') { return resolver(hostname, callback); } else { throw new Error('Unknown type "' + type_ + '"'); diff --git a/lib/events.js b/lib/events.js index 672131deed..cece093d38 100644 --- a/lib/events.js +++ b/lib/events.js @@ -1,7 +1,6 @@ 'use strict'; var domain; -const util = require('util'); function EventEmitter() { EventEmitter.init.call(this); @@ -40,14 +39,14 @@ EventEmitter.init = function() { // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. 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'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { - if (util.isUndefined(that._maxListeners)) + if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } @@ -82,13 +81,13 @@ EventEmitter.prototype.emit = function emit(type) { handler = this._events[type]; - if (util.isUndefined(handler)) + if (handler === undefined) return false; if (this.domain && this !== process) this.domain.enter(); - if (util.isFunction(handler)) { + if (typeof handler === 'function') { switch (arguments.length) { // fast cases case 1: @@ -108,7 +107,7 @@ EventEmitter.prototype.emit = function emit(type) { args[i - 1] = arguments[i]; handler.apply(this, args); } - } else if (util.isObject(handler)) { + } else if (handler !== null && typeof handler === 'object') { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) @@ -129,7 +128,7 @@ EventEmitter.prototype.emit = function emit(type) { EventEmitter.prototype.addListener = function addListener(type, listener) { var m; - if (!util.isFunction(listener)) + if (typeof listener !== 'function') throw TypeError('listener must be a function'); if (!this._events) @@ -139,13 +138,13 @@ EventEmitter.prototype.addListener = function addListener(type, listener) { // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, - util.isFunction(listener.listener) ? + typeof listener.listener === 'function' ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. 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. this._events[type].push(listener); else @@ -153,7 +152,8 @@ EventEmitter.prototype.addListener = function addListener(type, listener) { this._events[type] = [this._events[type], listener]; // 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); if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; @@ -171,7 +171,7 @@ EventEmitter.prototype.addListener = function addListener(type, listener) { EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function once(type, listener) { - if (!util.isFunction(listener)) + if (typeof listener !== 'function') throw TypeError('listener must be a function'); var fired = false; @@ -196,7 +196,7 @@ EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, position, length, i; - if (!util.isFunction(listener)) + if (typeof listener !== 'function') throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) @@ -207,12 +207,13 @@ EventEmitter.prototype.removeListener = position = -1; if (list === listener || - (util.isFunction(list.listener) && list.listener === listener)) { + (typeof list.listener === 'function' && + list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); - } else if (util.isObject(list)) { + } else if (list !== null && typeof list === 'object') { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { @@ -267,7 +268,7 @@ EventEmitter.prototype.removeAllListeners = listeners = this._events[type]; - if (util.isFunction(listeners)) { + if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (Array.isArray(listeners)) { // LIFO order @@ -283,7 +284,7 @@ EventEmitter.prototype.listeners = function listeners(type) { var ret; if (!this._events || !this._events[type]) ret = []; - else if (util.isFunction(this._events[type])) + else if (typeof this._events[type] === 'function') ret = [this._events[type]]; else ret = this._events[type].slice(); @@ -294,7 +295,7 @@ EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; - else if (util.isFunction(emitter._events[type])) + else if (typeof emitter._events[type] === 'function') ret = 1; else ret = emitter._events[type].length; diff --git a/lib/fs.js b/lib/fs.js index d7c82f9dbc..d967d22f59 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -57,14 +57,14 @@ function rethrow() { } 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 // for callbacks that are passed to the binding layer, callbacks that are // invoked from JS already run in the proper scope. function makeCallback(cb) { - if (!util.isFunction(cb)) { + if (typeof cb !== 'function') { return rethrow(); } @@ -218,11 +218,11 @@ fs.existsSync = function(path) { fs.readFile = function(path, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); - if (util.isFunction(options) || !options) { + if (!options || typeof options === 'function') { options = { encoding: null, flag: 'r' }; - } else if (util.isString(options)) { + } else if (typeof options === 'string') { options = { encoding: options, flag: 'r' }; - } else if (!util.isObject(options)) { + } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } @@ -317,9 +317,9 @@ fs.readFile = function(path, options, callback_) { fs.readFileSync = function(path, options) { if (!options) { options = { encoding: null, flag: 'r' }; - } else if (util.isString(options)) { + } else if (typeof options === 'string') { options = { encoding: options, flag: 'r' }; - } else if (!util.isObject(options)) { + } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } @@ -395,7 +395,7 @@ fs.readFileSync = function(path, options) { // Used by binding.open and friends function stringToFlags(flag) { // Only mess with strings - if (!util.isString(flag)) { + if (typeof flag !== 'string') { return flag; } @@ -448,9 +448,9 @@ fs.closeSync = function(fd) { }; function modeNum(m, def) { - if (util.isNumber(m)) + if (typeof m === 'number') return m; - if (util.isString(m)) + if (typeof m === 'string') return parseInt(m, 8); if (def) return modeNum(def); @@ -479,7 +479,7 @@ fs.openSync = function(path, flags, mode) { }; 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) var cb = arguments[4], encoding = arguments[3]; @@ -513,7 +513,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) { fs.readSync = function(fd, buffer, offset, length, position) { var legacy = false; - if (!util.isBuffer(buffer)) { + if (!(buffer instanceof Buffer)) { // legacy string interface (fd, length, position, encoding, callback) legacy = true; var encoding = arguments[3]; @@ -551,9 +551,9 @@ fs.write = function(fd, buffer, offset, length, position, callback) { callback(err, written || 0, buffer); } - if (util.isBuffer(buffer)) { + if (buffer instanceof Buffer) { // if no position is passed then assume null - if (util.isFunction(position)) { + if (typeof position === 'function') { callback = position; position = null; } @@ -563,10 +563,10 @@ fs.write = function(fd, buffer, offset, length, position, callback) { return binding.writeBuffer(fd, buffer, offset, length, position, req); } - if (util.isString(buffer)) + if (typeof buffer === 'string') buffer += ''; - if (!util.isFunction(position)) { - if (util.isFunction(offset)) { + if (typeof position !== 'function') { + if (typeof offset === 'function') { position = offset; offset = null; } else { @@ -585,14 +585,14 @@ fs.write = function(fd, buffer, offset, length, position, callback) { // OR // fs.writeSync(fd, string[, position[, encoding]]); fs.writeSync = function(fd, buffer, offset, length, position) { - if (util.isBuffer(buffer)) { - if (util.isUndefined(position)) + if (buffer instanceof Buffer) { + if (position === undefined) position = null; return binding.writeBuffer(fd, buffer, offset, length, position); } - if (!util.isString(buffer)) + if (typeof buffer !== 'string') buffer += ''; - if (util.isUndefined(offset)) + if (offset === undefined) offset = null; return binding.writeString(fd, buffer, offset, length, position); }; @@ -616,15 +616,15 @@ fs.renameSync = function(oldPath, newPath) { }; fs.truncate = function(path, len, callback) { - if (util.isNumber(path)) { + if (typeof path === 'number') { var req = new FSReqWrap(); req.oncomplete = callback; return fs.ftruncate(path, len, req); } - if (util.isFunction(len)) { + if (typeof len === 'function') { callback = len; len = 0; - } else if (util.isUndefined(len)) { + } else if (len === undefined) { len = 0; } @@ -642,11 +642,11 @@ fs.truncate = function(path, len, callback) { }; fs.truncateSync = function(path, len) { - if (util.isNumber(path)) { + if (typeof path === 'number') { // legacy return fs.ftruncateSync(path, len); } - if (util.isUndefined(len)) { + if (len === undefined) { len = 0; } // allow error to be thrown, but still close fd. @@ -660,10 +660,10 @@ fs.truncateSync = function(path, len) { }; fs.ftruncate = function(fd, len, callback) { - if (util.isFunction(len)) { + if (typeof len === 'function') { callback = len; len = 0; - } else if (util.isUndefined(len)) { + } else if (len === undefined) { len = 0; } var req = new FSReqWrap(); @@ -672,7 +672,7 @@ fs.ftruncate = function(fd, len, callback) { }; fs.ftruncateSync = function(fd, len) { - if (util.isUndefined(len)) { + if (len === undefined) { len = 0; } return binding.ftruncate(fd, len); @@ -712,7 +712,7 @@ fs.fsyncSync = function(fd) { }; fs.mkdir = function(path, mode, callback) { - if (util.isFunction(mode)) callback = mode; + if (typeof mode === 'function') callback = mode; callback = makeCallback(callback); if (!nullCheck(path, callback)) return; var req = new FSReqWrap(); @@ -806,7 +806,7 @@ function preprocessSymlinkDestination(path, type, linkPath) { } 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]); if (!nullCheck(destination, callback)) return; @@ -822,7 +822,7 @@ fs.symlink = function(destination, path, type_, callback) { }; fs.symlinkSync = function(destination, path, type) { - type = (util.isString(type) ? type : null); + type = (typeof type === 'string' ? type : null); nullCheck(destination); nullCheck(path); @@ -973,7 +973,7 @@ fs.chownSync = function(path, uid, gid) { // converts Date or number to a fractional UNIX timestamp function toUnixTimestamp(time) { - if (util.isNumber(time)) { + if (typeof time === 'number') { return time; } if (util.isDate(time)) { @@ -1043,11 +1043,11 @@ function writeAll(fd, buffer, offset, length, position, callback) { fs.writeFile = function(path, data, options, callback) { var callback = maybeCallback(arguments[arguments.length - 1]); - if (util.isFunction(options) || !options) { + if (!options || typeof options === 'function') { options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - } else if (util.isString(options)) { + } else if (typeof options === 'string') { options = { encoding: options, mode: 0o666, flag: 'w' }; - } else if (!util.isObject(options)) { + } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } @@ -1058,7 +1058,7 @@ fs.writeFile = function(path, data, options, callback) { if (openErr) { if (callback) callback(openErr); } else { - var buffer = util.isBuffer(data) ? data : new Buffer('' + data, + var buffer = (data instanceof Buffer) ? data : new Buffer('' + data, options.encoding || 'utf8'); var position = /a/.test(flag) ? null : 0; 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) { if (!options) { options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - } else if (util.isString(options)) { + } else if (typeof options === 'string') { options = { encoding: options, mode: 0o666, flag: 'w' }; - } else if (!util.isObject(options)) { + } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } @@ -1079,7 +1079,7 @@ fs.writeFileSync = function(path, data, options) { var flag = options.flag || 'w'; var fd = fs.openSync(path, flag, options.mode); - if (!util.isBuffer(data)) { + if (!(data instanceof Buffer)) { data = new Buffer('' + data, options.encoding || 'utf8'); } var written = 0; @@ -1098,11 +1098,11 @@ fs.writeFileSync = function(path, data, options) { fs.appendFile = function(path, data, options, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); - if (util.isFunction(options) || !options) { + if (!options || typeof options === 'function') { options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - } else if (util.isString(options)) { + } else if (typeof options === 'string') { options = { encoding: options, mode: 0o666, flag: 'a' }; - } else if (!util.isObject(options)) { + } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } @@ -1114,9 +1114,9 @@ fs.appendFile = function(path, data, options, callback_) { fs.appendFileSync = function(path, data, options) { if (!options) { options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - } else if (util.isString(options)) { + } else if (typeof options === 'string') { options = { encoding: options, mode: 0o666, flag: 'a' }; - } else if (!util.isObject(options)) { + } else if (typeof options !== 'object') { throw new TypeError('Bad arguments'); } if (!options.flag) @@ -1165,7 +1165,7 @@ fs.watch = function(filename) { var options; var listener; - if (util.isObject(arguments[1])) { + if (arguments[1] !== null && typeof arguments[1] === 'object') { options = arguments[1]; listener = arguments[2]; } else { @@ -1173,8 +1173,8 @@ fs.watch = function(filename) { listener = arguments[1]; } - if (util.isUndefined(options.persistent)) options.persistent = true; - if (util.isUndefined(options.recursive)) options.recursive = false; + if (options.persistent === undefined) options.persistent = true; + if (options.recursive === undefined) options.recursive = false; watcher = new FSWatcher(); watcher.start(filename, options.persistent, options.recursive); @@ -1247,7 +1247,7 @@ fs.watchFile = function(filename) { persistent: true }; - if (util.isObject(arguments[1])) { + if (arguments[1] !== null && typeof arguments[1] === 'object') { options = util._extend(options, arguments[1]); listener = arguments[2]; } else { @@ -1275,7 +1275,7 @@ fs.unwatchFile = function(filename, listener) { var stat = statWatchers[filename]; - if (util.isFunction(listener)) { + if (typeof listener === 'function') { stat.removeListener('change', listener); } else { stat.removeAllListeners('change'); @@ -1378,7 +1378,7 @@ fs.realpathSync = function realpathSync(p, cache) { linkTarget = seenLinks[id]; } } - if (util.isNull(linkTarget)) { + if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } @@ -1400,7 +1400,7 @@ fs.realpathSync = function realpathSync(p, cache) { fs.realpath = function realpath(p, cache, cb) { - if (!util.isFunction(cb)) { + if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } @@ -1561,13 +1561,13 @@ function ReadStream(path, options) { options.autoClose : true; this.pos = undefined; - if (!util.isUndefined(this.start)) { - if (!util.isNumber(this.start)) { + if (this.start !== undefined) { + if (typeof this.start !== 'number') { throw TypeError('start must be a Number'); } - if (util.isUndefined(this.end)) { + if (this.end === undefined) { this.end = Infinity; - } else if (!util.isNumber(this.end)) { + } else if (typeof this.end !== 'number') { throw TypeError('end must be a Number'); } @@ -1578,7 +1578,7 @@ function ReadStream(path, options) { this.pos = this.start; } - if (!util.isNumber(this.fd)) + if (typeof this.fd !== 'number') this.open(); this.on('end', function() { @@ -1609,7 +1609,7 @@ ReadStream.prototype.open = function() { }; ReadStream.prototype._read = function(n) { - if (!util.isNumber(this.fd)) + if (typeof this.fd !== 'number') return this.once('open', function() { this._read(n); }); @@ -1630,7 +1630,7 @@ ReadStream.prototype._read = function(n) { var toRead = Math.min(pool.length - pool.used, n); var start = pool.used; - if (!util.isUndefined(this.pos)) + if (this.pos !== undefined) toRead = Math.min(this.end - this.pos + 1, toRead); // 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); // move the pool positions, and internal position for reading. - if (!util.isUndefined(this.pos)) + if (this.pos !== undefined) this.pos += toRead; pool.used += toRead; @@ -1676,8 +1676,8 @@ ReadStream.prototype.close = function(cb) { var self = this; if (cb) this.once('close', cb); - if (this.closed || !util.isNumber(this.fd)) { - if (!util.isNumber(this.fd)) { + if (this.closed || typeof this.fd !== 'number') { + if (typeof this.fd !== 'number') { this.once('open', close); return; } @@ -1725,8 +1725,8 @@ function WriteStream(path, options) { this.pos = undefined; this.bytesWritten = 0; - if (!util.isUndefined(this.start)) { - if (!util.isNumber(this.start)) { + if (this.start !== undefined) { + if (typeof this.start !== 'number') { throw TypeError('start must be a Number'); } if (this.start < 0) { @@ -1736,7 +1736,7 @@ function WriteStream(path, options) { this.pos = this.start; } - if (!util.isNumber(this.fd)) + if (typeof this.fd !== 'number') this.open(); // dispose on finish. @@ -1761,10 +1761,10 @@ WriteStream.prototype.open = function() { WriteStream.prototype._write = function(data, encoding, cb) { - if (!util.isBuffer(data)) + if (!(data instanceof Buffer)) return this.emit('error', new Error('Invalid data')); - if (!util.isNumber(this.fd)) + if (typeof this.fd !== 'number') return this.once('open', function() { this._write(data, encoding, cb); }); @@ -1779,7 +1779,7 @@ WriteStream.prototype._write = function(data, encoding, cb) { cb(); }); - if (!util.isUndefined(this.pos)) + if (this.pos !== undefined) this.pos += data.length; }; @@ -1817,10 +1817,10 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) { // parse arguments if (arg1) { - if (util.isString(arg1)) { + if (typeof arg1 === 'string') { encoding = arg1; cb = arg2; - } else if (util.isFunction(arg1)) { + } else if (typeof arg1 === 'function') { cb = arg1; } else { throw new Error('bad arg'); @@ -1829,7 +1829,7 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) { assertEncoding(encoding); // Change strings to buffers. SLOW - if (util.isString(data)) { + if (typeof data === 'string') { data = new Buffer(data, encoding); } diff --git a/lib/https.js b/lib/https.js index acbbe0b6c2..4ee15b2537 100644 --- a/lib/https.js +++ b/lib/https.js @@ -4,7 +4,7 @@ const tls = require('tls'); const url = require('url'); const http = require('http'); const util = require('util'); -const inherits = require('util').inherits; +const inherits = util.inherits; const debug = util.debuglog('https'); function Server(opts, requestListener) { @@ -41,21 +41,21 @@ exports.createServer = function(opts, requestListener) { // HTTPS agents. function createConnection(port, host, options) { - if (util.isObject(port)) { + if (port !== null && typeof port === 'object') { options = port; - } else if (util.isObject(host)) { + } else if (host !== null && typeof host === 'object') { options = host; - } else if (util.isObject(options)) { + } else if (options !== null && typeof options === 'object') { options = options; } else { options = {}; } - if (util.isNumber(port)) { + if (typeof port === 'number') { options.port = port; } - if (util.isString(host)) { + if (typeof host === 'string') { options.host = host; } @@ -96,7 +96,7 @@ Agent.prototype.getName = function(options) { name += options.pfx; name += ':'; - if (!util.isUndefined(options.rejectUnauthorized)) + if (options.rejectUnauthorized !== undefined) name += options.rejectUnauthorized; return name; @@ -108,7 +108,7 @@ exports.globalAgent = globalAgent; exports.Agent = Agent; exports.request = function(options, cb) { - if (util.isString(options)) { + if (typeof options === 'string') { options = url.parse(options); } else { options = util._extend({}, options); diff --git a/lib/module.js b/lib/module.js index 07c32b7eee..3f42975a63 100644 --- a/lib/module.js +++ b/lib/module.js @@ -347,7 +347,7 @@ Module.prototype.load = function(filename) { // `exports` property. Module.prototype.require = function(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); }; diff --git a/lib/net.js b/lib/net.js index 13a3ca424b..1cd8b6da35 100644 --- a/lib/net.js +++ b/lib/net.js @@ -45,7 +45,7 @@ function createHandle(fd) { const debug = util.debuglog('net'); function isPipeName(s) { - return util.isString(s) && toNumber(s) === false; + return typeof s === 'string' && toNumber(s) === false; } exports.createServer = function() { @@ -77,7 +77,7 @@ exports.connect = exports.createConnection = function() { function normalizeConnectArgs(args) { var options = {}; - if (util.isObject(args[0])) { + if (args[0] !== null && typeof args[0] === 'object') { // connect(options, [cb]) options = args[0]; } else if (isPipeName(args[0])) { @@ -86,13 +86,13 @@ function normalizeConnectArgs(args) { } else { // connect(port, [host], [cb]) options.port = args[0]; - if (util.isString(args[1])) { + if (typeof args[1] === 'string') { options.host = args[1]; } } var cb = args[args.length - 1]; - return util.isFunction(cb) ? [options, cb] : [options]; + return typeof cb === 'function' ? [options, cb] : [options]; } exports._normalizeConnectArgs = normalizeConnectArgs; @@ -122,16 +122,16 @@ function Socket(options) { this._handle = null; this._host = null; - if (util.isNumber(options)) + if (typeof options === 'number') options = { fd: options }; // Legacy interface. - else if (util.isUndefined(options)) + else if (options === undefined) options = {}; stream.Duplex.call(this, options); if (options.handle) { this._handle = options.handle; // private - } else if (!util.isUndefined(options.fd)) { + } else if (options.fd !== undefined) { this._handle = createHandle(options.fd); this._handle.open(options.fd); 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' // is overly vague, and makes it seem like the user's code is to blame. function writeAfterFIN(chunk, encoding, cb) { - if (util.isFunction(encoding)) { + if (typeof encoding === 'function') { cb = encoding; encoding = null; } @@ -271,7 +271,7 @@ function writeAfterFIN(chunk, encoding, cb) { var self = this; // TODO: defer error events consistently everywhere, not just the cb self.emit('error', er); - if (util.isFunction(cb)) { + if (typeof cb === 'function') { process.nextTick(function() { cb(er); }); @@ -324,7 +324,7 @@ Socket.prototype._onTimeout = function() { Socket.prototype.setNoDelay = function(enable) { // backwards compatibility: assume true when `enable` is omitted 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) { - if (!util.isString(chunk) && !util.isBuffer(chunk)) + if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) throw new TypeError('invalid data'); 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; } else { var enc; - if (util.isBuffer(data)) { + if (data instanceof Buffer) { req.buffer = data; // Keep reference alive. enc = 'buffer'; } else { @@ -713,14 +713,14 @@ Socket.prototype.__defineGetter__('bytesWritten', function() { encoding = this._pendingEncoding; state.getBuffer().forEach(function(el) { - if (util.isBuffer(el.chunk)) + if (el.chunk instanceof Buffer) bytes += el.chunk.length; else bytes += Buffer.byteLength(el.chunk, el.encoding); }); if (data) { - if (util.isBuffer(data)) + if (data instanceof Buffer) bytes += data.length; else bytes += Buffer.byteLength(data, encoding); @@ -830,7 +830,7 @@ Socket.prototype.connect = function(options, cb) { if (this.write !== Socket.prototype.write) this.write = Socket.prototype.write; - if (!util.isObject(options)) { + if (options === null || typeof options !== 'object') { // Old API: // connect(port, [host], [cb]) // connect(path, [cb]); @@ -859,7 +859,7 @@ Socket.prototype.connect = function(options, cb) { initSocketHandle(this); } - if (util.isFunction(cb)) { + if (typeof cb === 'function') { self.once('connect', cb); } @@ -885,7 +885,7 @@ Socket.prototype.connect = function(options, cb) { if (localAddress && !exports.isIP(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); if (port <= 0 || port > 65535) @@ -998,13 +998,13 @@ function Server(/* [ options, ] listener */) { var options; - if (util.isFunction(arguments[0])) { + if (typeof arguments[0] === 'function') { options = {}; self.on('connection', arguments[0]); } else { options = arguments[0] || {}; - if (util.isFunction(arguments[1])) { + if (typeof arguments[1] === 'function') { self.on('connection', arguments[1]); } } @@ -1052,7 +1052,7 @@ var createServerHandle = exports._createServerHandle = var handle; var isTCP = false; - if (util.isNumber(fd) && fd >= 0) { + if (typeof fd === 'number' && fd >= 0) { try { handle = createHandle(fd); } @@ -1117,10 +1117,10 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { var rval = null; - if (!address && !util.isNumber(fd)) { + if (!address && typeof fd !== 'number') { rval = createServerHandle('::', port, 6, fd); - if (util.isNumber(rval)) { + if (typeof rval === 'number') { rval = null; address = '0.0.0.0'; addressType = 4; @@ -1133,7 +1133,7 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { if (rval === null) rval = createServerHandle(address, port, addressType, fd); - if (util.isNumber(rval)) { + if (typeof rval === 'number') { var error = exceptionWithHostPort(rval, 'listen', address, port); process.nextTick(function() { self.emit('error', error); @@ -1212,7 +1212,7 @@ Server.prototype.listen = function() { var self = this; var lastArg = arguments[arguments.length - 1]; - if (util.isFunction(lastArg)) { + if (typeof lastArg === 'function') { self.once('listening', lastArg); } @@ -1224,24 +1224,24 @@ Server.prototype.listen = function() { 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. 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]; h = h._handle || h.handle || h; if (h instanceof TCP) { self._handle = h; 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); } else { // The first argument is a configuration object if (h.backlog) backlog = h.backlog; - if (util.isNumber(h.port)) { + if (typeof h.port === 'number') { if (h.host) listenAfterLookup(h.port, h.host, backlog, h.exclusive); else @@ -1258,9 +1258,9 @@ Server.prototype.listen = function() { var pipeName = self._pipeName = arguments[0]; listen(self, pipeName, -1, -1, backlog); - } else if (util.isUndefined(arguments[1]) || - util.isFunction(arguments[1]) || - util.isNumber(arguments[1])) { + } else if (arguments[1] === undefined || + typeof arguments[1] === 'function' || + typeof arguments[1] === 'number') { // The first argument is the port, no IP given. listen(self, null, port, 4, backlog); @@ -1456,11 +1456,11 @@ if (process.platform === 'win32') { var simultaneousAccepts; exports._setSimultaneousAccepts = function(handle) { - if (util.isUndefined(handle)) { + if (handle === undefined) { return; } - if (util.isUndefined(simultaneousAccepts)) { + if (simultaneousAccepts === undefined) { simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS && process.env.NODE_MANY_ACCEPTS !== '0'); } diff --git a/lib/path.js b/lib/path.js index f1acb06b45..6259c5fd1d 100644 --- a/lib/path.js +++ b/lib/path.js @@ -1,8 +1,6 @@ 'use strict'; const isWindows = process.platform === 'win32'; -const util = require('util'); - // resolves . and .. elements in a path array with directory names there // must be no slashes or device names (c:\) in the array @@ -87,7 +85,7 @@ win32.resolve = function() { } // Skip empty and invalid entries - if (!util.isString(path)) { + if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; @@ -176,7 +174,7 @@ win32.isAbsolute = function(path) { win32.join = function() { function f(p) { - if (!util.isString(p)) { + if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; @@ -265,7 +263,7 @@ win32.relative = function(from, to) { win32._makeLong = function(path) { // Note: this will *probably* throw somewhere. - if (!util.isString(path)) + if (typeof path !== 'string') return path; if (!path) { @@ -323,7 +321,7 @@ win32.extname = function(path) { win32.format = function(pathObject) { - if (!util.isObject(pathObject)) { + if (pathObject === null || typeof pathObject !== 'object') { throw new TypeError( "Parameter 'pathObject' must be an object, not " + typeof pathObject ); @@ -331,7 +329,7 @@ win32.format = function(pathObject) { var root = pathObject.root || ''; - if (!util.isString(root)) { + if (typeof root !== 'string') { throw new TypeError( "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root @@ -353,7 +351,7 @@ win32.format = function(pathObject) { win32.parse = function(pathString) { - if (!util.isString(pathString)) { + if (typeof pathString !== 'string') { throw new TypeError( "Parameter 'pathString' must be a string, not " + typeof pathString ); @@ -398,7 +396,7 @@ posix.resolve = function() { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries - if (!util.isString(path)) { + if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; @@ -447,7 +445,7 @@ posix.join = function() { var path = ''; for (var i = 0; i < arguments.length; i++) { var segment = arguments[i]; - if (!util.isString(segment)) { + if (typeof segment !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } if (segment) { @@ -546,7 +544,7 @@ posix.extname = function(path) { posix.format = function(pathObject) { - if (!util.isObject(pathObject)) { + if (pathObject === null || typeof pathObject !== 'object') { throw new TypeError( "Parameter 'pathObject' must be an object, not " + typeof pathObject ); @@ -554,7 +552,7 @@ posix.format = function(pathObject) { var root = pathObject.root || ''; - if (!util.isString(root)) { + if (typeof root !== 'string') { throw new TypeError( "'pathObject.root' must be a string or undefined, not " + typeof pathObject.root @@ -568,7 +566,7 @@ posix.format = function(pathObject) { posix.parse = function(pathString) { - if (!util.isString(pathString)) { + if (typeof pathString !== 'string') { throw new TypeError( "Parameter 'pathString' must be a string, not " + typeof pathString ); diff --git a/lib/querystring.js b/lib/querystring.js index 5270bc6f1a..b574978bc7 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -3,8 +3,6 @@ 'use strict'; const QueryString = exports; -const util = require('util'); - // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. @@ -100,11 +98,13 @@ QueryString.escape = function(str) { }; var stringifyPrimitive = function(v) { - if (util.isString(v)) + let type = typeof v; + + if (type === 'string') return v; - if (util.isBoolean(v)) + if (type === 'boolean') return v ? 'true' : 'false'; - if (util.isNumber(v)) + if (type === 'number') return isFinite(v) ? v : ''; return ''; }; @@ -119,7 +119,7 @@ QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) { encode = options.encodeURIComponent; } - if (util.isObject(obj)) { + if (obj !== null && typeof obj === 'object') { var keys = Object.keys(obj); var fields = []; @@ -128,7 +128,7 @@ QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) { var v = obj[k]; var ks = encode(stringifyPrimitive(k)) + eq; - if (util.isArray(v)) { + if (Array.isArray(v)) { for (var j = 0; j < v.length; j++) fields.push(ks + encode(stringifyPrimitive(v[j]))); } else { @@ -146,7 +146,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { eq = eq || '='; var obj = {}; - if (!util.isString(qs) || qs.length === 0) { + if (typeof qs !== 'string' || qs.length === 0) { return obj; } @@ -154,7 +154,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { qs = qs.split(sep); var maxKeys = 1000; - if (options && util.isNumber(options.maxKeys)) { + if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } @@ -192,7 +192,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { if (!hasOwnProperty(obj, k)) { obj[k] = v; - } else if (util.isArray(obj[k])) { + } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; diff --git a/lib/readline.js b/lib/readline.js index 1a159c9a1b..04e3f97aac 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -43,13 +43,13 @@ function Interface(input, output, completer, terminal) { completer = completer || function() { return []; }; - if (!util.isFunction(completer)) { + if (typeof completer !== 'function') { throw new TypeError('Argument \'completer\' must be a function'); } // backwards compat; check the isTTY prop of the output stream // when `terminal` was not specified - if (util.isUndefined(terminal) && !util.isNullOrUndefined(output)) { + if (terminal === undefined && !(output === null || output === undefined)) { terminal = !!output.isTTY; } @@ -72,14 +72,15 @@ function Interface(input, output, completer, terminal) { } 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.close(); } 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.close(); @@ -123,13 +124,13 @@ function Interface(input, output, completer, terminal) { this.history = []; this.historyIndex = -1; - if (!util.isNullOrUndefined(output)) + if (output !== null && output !== undefined) output.on('resize', onresize); self.once('close', function() { input.removeListener('keypress', onkeypress); input.removeListener('end', ontermend); - if (!util.isNullOrUndefined(output)) { + if (output !== null && output !== undefined) { output.removeListener('resize', onresize); } }); @@ -153,7 +154,7 @@ Interface.prototype.setPrompt = function(prompt) { Interface.prototype._setRawMode = function(mode) { - if (util.isFunction(this.input.setRawMode)) { + if (typeof this.input.setRawMode === 'function') { return this.input.setRawMode(mode); } }; @@ -171,7 +172,7 @@ Interface.prototype.prompt = function(preserveCursor) { Interface.prototype.question = function(query, cb) { - if (util.isFunction(cb)) { + if (typeof cb === 'function') { if (this._questionCallback) { this.prompt(); } else { @@ -196,10 +197,10 @@ Interface.prototype._onLine = function(line) { }; Interface.prototype._writeToOutput = function _writeToOutput(stringToWrite) { - if (!util.isString(stringToWrite)) + if (typeof stringToWrite !== '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); }; @@ -296,7 +297,7 @@ Interface.prototype.write = function(d, key) { // \r\n, \n, or \r followed by something other than \n const lineEnding = /\r?\n|\r(?!\n)/; Interface.prototype._normalWrite = function(b) { - if (util.isUndefined(b)) { + if (b === undefined) { return; } var string = this._decoder.write(b); @@ -854,7 +855,7 @@ Interface.prototype._ttyWrite = function(s, key) { break; default: - if (util.isBuffer(s)) + if (s instanceof Buffer) s = s.toString('utf-8'); if (s) { @@ -952,8 +953,8 @@ const escapeCodeReAnywhere = new RegExp([ ].join('|')); function emitKeys(stream, s) { - if (util.isBuffer(s)) { - if (s[0] > 127 && util.isUndefined(s[1])) { + if (s instanceof Buffer) { + if (s[0] > 127 && s[1] === undefined) { s[0] -= 128; s = '\x1b' + s.toString(stream.encoding || 'utf-8'); } else { @@ -1143,7 +1144,7 @@ function emitKeys(stream, s) { } // Don't emit a key if no name was found - if (util.isUndefined(key.name)) { + if (key.name === undefined) { key = undefined; } @@ -1163,16 +1164,16 @@ function emitKeys(stream, s) { */ function cursorTo(stream, x, y) { - if (util.isNullOrUndefined(stream)) + if (stream === null || stream === undefined) return; - if (!util.isNumber(x) && !util.isNumber(y)) + if (typeof x !== 'number' && typeof y !== 'number') return; - if (!util.isNumber(x)) + if (typeof x !== 'number') 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'); } else { stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); @@ -1186,7 +1187,7 @@ exports.cursorTo = cursorTo; */ function moveCursor(stream, dx, dy) { - if (util.isNullOrUndefined(stream)) + if (stream === null || stream === undefined) return; if (dx < 0) { @@ -1212,7 +1213,7 @@ exports.moveCursor = moveCursor; */ function clearLine(stream, dir) { - if (util.isNullOrUndefined(stream)) + if (stream === null || stream === undefined) return; if (dir < 0) { @@ -1234,7 +1235,7 @@ exports.clearLine = clearLine; */ function clearScreenDown(stream) { - if (util.isNullOrUndefined(stream)) + if (stream === null || stream === undefined) return; stream.write('\x1b[0J'); diff --git a/lib/repl.js b/lib/repl.js index 64d99b0001..0a63f325c6 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -63,7 +63,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { } var options, input, output, dom; - if (util.isObject(prompt)) { + if (prompt !== null && typeof prompt === 'object') { // an options object was given options = prompt; stream = options.stream || options.socket; @@ -74,7 +74,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { ignoreUndefined = options.ignoreUndefined; prompt = options.prompt; 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'); } else { options = {}; @@ -176,7 +176,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { options.terminal ]); - self.setPrompt(!util.isUndefined(prompt) ? prompt : '> '); + self.setPrompt(prompt !== undefined ? prompt : '> '); this.commands = {}; defineDefaultCommands(this); @@ -184,7 +184,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { // figure out which "writer" function to use self.writer = options.writer || exports.writer; - if (util.isUndefined(options.useColors)) { + if (options.useColors === undefined) { options.useColors = self.terminal; } self.useColors = !!options.useColors; @@ -303,7 +303,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { self.bufferedCommand = ''; // 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.outputStream.write(self.writer(ret) + '\n'); } @@ -431,7 +431,7 @@ const simpleExpressionRE = // getter code. REPLServer.prototype.complete = function(line, callback) { // 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 var tmp = this.lines.slice(); // 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) { if (err || !globals) { addStandardGlobals(completionGroups, filter); - } else if (util.isArray(globals[0])) { + } else if (Array.isArray(globals[0])) { // Add grouped globals globals.forEach(function(group) { completionGroups.push(group); @@ -590,19 +590,19 @@ REPLServer.prototype.complete = function(line, callback) { // if (e) console.log(e); if (obj != null) { - if (util.isObject(obj) || util.isFunction(obj)) { + if (typeof obj === 'object' || typeof obj === 'function') { memberGroups.push(Object.getOwnPropertyNames(obj)); } // works for non-objects try { var sentinel = 5; var p; - if (util.isObject(obj) || util.isFunction(obj)) { + if (typeof obj === 'object' || typeof obj === 'function') { p = Object.getPrototypeOf(obj); } else { p = obj.constructor ? obj.constructor.prototype : null; } - while (!util.isNull(p)) { + while (p !== null) { memberGroups.push(Object.getOwnPropertyNames(p)); p = Object.getPrototypeOf(p); // Circular refs possible? Let's guard against that. @@ -701,9 +701,9 @@ REPLServer.prototype.parseREPLKeyword = function(keyword, rest) { REPLServer.prototype.defineCommand = function(keyword, cmd) { - if (util.isFunction(cmd)) { + if (typeof cmd === 'function') { 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'); } this.commands[keyword] = cmd; diff --git a/lib/smalloc.js b/lib/smalloc.js index beccba71a4..b6eb21fbc3 100644 --- a/lib/smalloc.js +++ b/lib/smalloc.js @@ -40,10 +40,10 @@ Object.defineProperty(exports, 'Types', { function alloc(n, obj, type) { n = n >>> 0; - if (util.isUndefined(obj)) + if (obj === undefined) obj = {}; - if (util.isNumber(obj)) { + if (typeof obj === 'number') { type = obj >>> 0; obj = {}; } else if (util.isPrimitive(obj)) { @@ -53,7 +53,7 @@ function alloc(n, obj, type) { // 1 == v8::kExternalUint8Array, 9 == v8::kExternalUint8ClampedArray if (type < 1 || type > 9) throw new TypeError('unknown external array type: ' + type); - if (util.isArray(obj)) + if (Array.isArray(obj)) throw new TypeError('Arrays are not supported'); if (n > kMaxLength) throw new RangeError('n > kMaxLength'); @@ -65,7 +65,7 @@ function alloc(n, obj, type) { function dispose(obj) { if (util.isPrimitive(obj)) throw new TypeError('obj must be an Object'); - if (util.isBuffer(obj)) + if (obj instanceof Buffer) throw new TypeError('obj cannot be a Buffer'); if (smalloc.isTypedArray(obj)) throw new TypeError('obj cannot be a typed array'); diff --git a/lib/stream.js b/lib/stream.js index bbd6bc5aae..dd381d9737 100644 --- a/lib/stream.js +++ b/lib/stream.js @@ -65,7 +65,7 @@ Stream.prototype.pipe = function(dest, options) { if (didOnEnd) return; 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. diff --git a/lib/tls.js b/lib/tls.js index d52adbabc8..0e13516add 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -36,7 +36,7 @@ exports.getCiphers = function() { // ("\x06spdy/2\x08http/1.1\x08http/1.0") exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { // 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) { return p + 1 + Buffer.byteLength(c); }, 0)); @@ -53,7 +53,7 @@ exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { } // If it's already a Buffer - store it - if (util.isBuffer(NPNProtocols)) { + if (NPNProtocols instanceof Buffer) { out.NPNProtocols = NPNProtocols; } }; @@ -160,7 +160,7 @@ exports.checkServerIdentity = function checkServerIdentity(host, cert) { // RFC6125 if (matchCN) { var commonNames = cert.subject.CN; - if (util.isArray(commonNames)) { + if (Array.isArray(commonNames)) { for (var i = 0, k = commonNames.length; i < k; ++i) { dnsNames.push(regexpify(commonNames[i], true)); } @@ -208,7 +208,7 @@ exports.parseCertString = function parseCertString(s) { var key = parts[i].slice(0, sepIndex); var value = parts[i].slice(sepIndex + 1); if (key in out) { - if (!util.isArray(out[key])) { + if (!Array.isArray(out[key])) { out[key] = [out[key]]; } out[key].push(value); diff --git a/lib/tty.js b/lib/tty.js index 84731a5e75..1241d52535 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -1,11 +1,10 @@ 'use strict'; -const inherits = require('util').inherits; +const util = require('util'); const net = require('net'); const TTY = process.binding('tty_wrap').TTY; const isTTY = process.binding('tty_wrap').isTTY; -const util = require('util'); - +const inherits = util.inherits; const errnoException = util._errnoException; diff --git a/lib/url.js b/lib/url.js index 50126ae9bf..65012cd7c4 100644 --- a/lib/url.js +++ b/lib/url.js @@ -1,7 +1,6 @@ 'use strict'; const punycode = require('punycode'); -const util = require('util'); exports.parse = urlParse; exports.resolve = urlResolve; @@ -79,7 +78,7 @@ const slashedProtocol = { const querystring = require('querystring'); 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; u.parse(url, parseQueryString, slashesDenoteHost); @@ -87,7 +86,7 @@ function urlParse(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); } @@ -353,7 +352,7 @@ function urlFormat(obj) { // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // 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); return obj.format(); } @@ -383,8 +382,8 @@ Url.prototype.format = function() { } } - if (this.query && - util.isObject(this.query) && + if (this.query !== null && + typeof this.query === 'object' && Object.keys(this.query).length) { query = querystring.stringify(this.query); } @@ -428,7 +427,7 @@ function urlResolveObject(source, relative) { } Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { + if (typeof relative === 'string') { var rel = new Url(); rel.parse(relative, false, true); relative = rel; @@ -574,7 +573,7 @@ Url.prototype.resolveObject = function(relative) { srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { + } else if (relative.search !== null && relative.search !== undefined) { // just pull out the search. // like href='?foo'. // 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.query = relative.query; //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.search ? result.search : ''); } @@ -687,7 +686,7 @@ Url.prototype.resolveObject = function(relative) { } //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.search ? result.search : ''); } diff --git a/lib/util.js b/lib/util.js index 7c3e03c24e..f84f528ce3 100644 --- a/lib/util.js +++ b/lib/util.js @@ -2,7 +2,7 @@ const formatRegExp = /%[sdj%]/g; exports.format = function(f) { - if (!isString(f)) { + if (typeof f !== 'string') { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); @@ -30,7 +30,7 @@ exports.format = function(f) { } }); for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { + if (x === null || typeof x !== 'object') { str += ' ' + x; } else { str += ' ' + inspect(x); @@ -45,7 +45,7 @@ exports.format = function(f) { // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { + if (global.process === undefined) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; @@ -77,7 +77,7 @@ exports.deprecate = function(fn, msg) { var debugs = {}; var debugEnviron; exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) + if (debugEnviron === undefined) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { @@ -112,7 +112,7 @@ function inspect(obj, opts) { // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { + if (typeof opts === 'boolean') { // legacy... ctx.showHidden = opts; } else if (opts) { @@ -120,10 +120,10 @@ function inspect(obj, opts) { exports._extend(ctx, opts); } // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.showHidden === undefined) ctx.showHidden = false; + if (ctx.depth === undefined) ctx.depth = 2; + if (ctx.colors === undefined) ctx.colors = false; + if (ctx.customInspect === undefined) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; 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 if (ctx.customInspect && value && - isFunction(value.inspect) && + typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { + if (typeof ret !== 'string') { ret = formatValue(ctx, ret, recurseTimes); } return ret; @@ -236,7 +236,7 @@ function formatValue(ctx, value, recurseTimes) { // ignore... } - if (isString(raw)) { + if (typeof raw === 'string') { // for boxed Strings, we have to remove the 0-n indexed entries, // since they just noisey up the output and are redundant keys = keys.filter(function(key) { @@ -246,7 +246,7 @@ function formatValue(ctx, value, recurseTimes) { // Some type of object without properties can be shortcutted. if (keys.length === 0) { - if (isFunction(value)) { + if (typeof value === 'function') { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } @@ -260,15 +260,15 @@ function formatValue(ctx, value, recurseTimes) { return formatError(value); } // now check the `raw` value to handle boxed primitives - if (isString(raw)) { + if (typeof raw === 'string') { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[String: ' + formatted + ']', 'string'); } - if (isNumber(raw)) { + if (typeof raw === 'number') { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[Number: ' + formatted + ']', 'number'); } - if (isBoolean(raw)) { + if (typeof raw === 'boolean') { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean'); } @@ -277,13 +277,13 @@ function formatValue(ctx, value, recurseTimes) { var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array - if (isArray(value)) { + if (Array.isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions - if (isFunction(value)) { + if (typeof value === 'function') { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } @@ -304,19 +304,19 @@ function formatValue(ctx, value, recurseTimes) { } // Make boxed primitive Strings look like such - if (isString(raw)) { + if (typeof raw === 'string') { formatted = formatPrimitiveNoColor(ctx, raw); base = ' ' + '[String: ' + formatted + ']'; } // Make boxed primitive Numbers look like such - if (isNumber(raw)) { + if (typeof raw === 'number') { formatted = formatPrimitiveNoColor(ctx, raw); base = ' ' + '[Number: ' + formatted + ']'; } // Make boxed primitive Booleans look like such - if (isBoolean(raw)) { + if (typeof raw === 'boolean') { formatted = formatPrimitiveNoColor(ctx, raw); base = ' ' + '[Boolean: ' + formatted + ']'; } @@ -351,28 +351,32 @@ function formatValue(ctx, value, recurseTimes) { function formatPrimitive(ctx, value) { - if (isUndefined(value)) + if (value === 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, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } - if (isNumber(value)) { + if (type === 'number') { // 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 . if (value === 0 && 1 / value < 0) return ctx.stylize('-0', 'number'); return ctx.stylize('' + value, 'number'); } - if (isBoolean(value)) + if (type === '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 - if (isSymbol(value)) + if (type === 'symbol') return ctx.stylize(value.toString(), 'symbol'); } @@ -402,7 +406,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { } } keys.forEach(function(key) { - if (isSymbol(key) || !key.match(/^\d+$/)) { + if (typeof key === 'symbol' || !key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } @@ -426,7 +430,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { } } if (!hasOwnProperty(visibleKeys, key)) { - if (isSymbol(key)) { + if (typeof key === 'symbol') { name = '[' + ctx.stylize(key.toString(), 'symbol') + ']'; } else { name = '[' + key + ']'; @@ -434,7 +438,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { + if (recurseTimes === null) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); @@ -454,7 +458,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { str = ctx.stylize('[Circular]', 'special'); } } - if (isUndefined(name)) { + if (name === undefined) { if (array && key.match(/^\d+$/)) { return str; } @@ -508,7 +512,7 @@ function isNull(arg) { exports.isNull = isNull; function isNullOrUndefined(arg) { - return arg == null; + return arg === null || arg === undefined; } exports.isNullOrUndefined = isNullOrUndefined; @@ -528,27 +532,29 @@ function isSymbol(arg) { exports.isSymbol = isSymbol; function isUndefined(arg) { - return arg === void 0; + return arg === undefined; } exports.isUndefined = isUndefined; function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + return re !== null && typeof re === 'object' && + objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { - return typeof arg === 'object' && arg !== null; + return arg !== null && typeof arg === 'object'; } exports.isObject = isObject; function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; + return d !== null && typeof d === 'object' && + objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { - return isObject(e) && + return e !== null && typeof e === 'object' && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; @@ -629,7 +635,7 @@ exports.inherits = function(ctor, superCtor) { exports._extend = function(origin, add) { // 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 i = keys.length; @@ -724,7 +730,7 @@ exports.pump = exports.deprecate(function(readStream, writeStream, callback) { var uv; 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 message = syscall + ' ' + errname; if (original) diff --git a/lib/vm.js b/lib/vm.js index 8a190fa9ed..b4a2b99990 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -2,7 +2,6 @@ const binding = process.binding('contextify'); const Script = binding.ContextifyScript; -const util = require('util'); // The binding provides a few useful primitives: // - ContextifyScript(code, { filename = "evalmachine.anonymous", @@ -26,7 +25,7 @@ exports.createScript = function(code, options) { }; exports.createContext = function(sandbox) { - if (util.isUndefined(sandbox)) { + if (sandbox === undefined) { sandbox = {}; } else if (binding.isContext(sandbox)) { return sandbox; diff --git a/lib/zlib.js b/lib/zlib.js index 53e8eb66fd..14ccf8f959 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -92,7 +92,7 @@ exports.createUnzip = function(o) { // Convenience methods. // compress/decompress a string or buffer in one step. exports.deflate = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -104,7 +104,7 @@ exports.deflateSync = function(buffer, opts) { }; exports.gzip = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -116,7 +116,7 @@ exports.gzipSync = function(buffer, opts) { }; exports.deflateRaw = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -128,7 +128,7 @@ exports.deflateRawSync = function(buffer, opts) { }; exports.unzip = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -140,7 +140,7 @@ exports.unzipSync = function(buffer, opts) { }; exports.inflate = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -152,7 +152,7 @@ exports.inflateSync = function(buffer, opts) { }; exports.gunzip = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -164,7 +164,7 @@ exports.gunzipSync = function(buffer, opts) { }; exports.inflateRaw = function(buffer, opts, callback) { - if (util.isFunction(opts)) { + if (typeof opts === 'function') { callback = opts; opts = {}; } @@ -209,9 +209,9 @@ function zlibBuffer(engine, buffer, callback) { } function zlibBufferSync(engine, buffer) { - if (util.isString(buffer)) + if (typeof buffer === 'string') buffer = new Buffer(buffer); - if (!util.isBuffer(buffer)) + if (!(buffer instanceof Buffer)) throw new TypeError('Not a string or buffer'); var flushFlag = binding.Z_FINISH; @@ -327,7 +327,7 @@ function Zlib(opts, mode) { } if (opts.dictionary) { - if (!util.isBuffer(opts.dictionary)) { + if (!(opts.dictionary instanceof Buffer)) { 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; - if (util.isNumber(opts.level)) level = opts.level; + if (typeof opts.level === 'number') level = opts.level; 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, level, @@ -414,7 +414,7 @@ Zlib.prototype._flush = function(callback) { Zlib.prototype.flush = function(kind, callback) { var ws = this._writableState; - if (util.isFunction(kind) || (util.isUndefined(kind) && !callback)) { + if (typeof kind === 'function' || (kind === undefined && !callback)) { callback = kind; kind = binding.Z_FULL_FLUSH; } @@ -459,7 +459,7 @@ Zlib.prototype._transform = function(chunk, encoding, cb) { var ending = ws.ending || ws.ended; 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')); if (this._closed) @@ -490,7 +490,7 @@ Zlib.prototype._processChunk = function(chunk, flushFlag, cb) { var self = this; - var async = util.isFunction(cb); + var async = typeof cb === 'function'; if (!async) { var buffers = [];