diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js index bf498f623c743d..06724f6972393e 100644 --- a/lib/_stream_duplex.js +++ b/lib/_stream_duplex.js @@ -7,11 +7,11 @@ module.exports = Duplex; -const util = require('util'); const Readable = require('_stream_readable'); const Writable = require('_stream_writable'); +const inherits = require('internal/inherits'); -util.inherits(Duplex, Readable); +inherits(Duplex, Readable); var keys = Object.keys(Writable.prototype); for (var v = 0; v < keys.length; v++) { diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js index 30952d436e3d38..411b90481da5f1 100644 --- a/lib/_stream_passthrough.js +++ b/lib/_stream_passthrough.js @@ -7,8 +7,8 @@ module.exports = PassThrough; const Transform = require('_stream_transform'); -const util = require('util'); -util.inherits(PassThrough, Transform); +const inherits = require('internal/inherits'); +inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index c6bd0c16659d1e..bcc01f5c791c04 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -3,14 +3,16 @@ module.exports = Readable; Readable.ReadableState = ReadableState; -const EE = require('events').EventEmitter; -const Stream = require('stream'); const Buffer = require('buffer').Buffer; -const util = require('util'); -const debug = util.debuglog('stream'); +const EE = require('events').EventEmitter; +const Stream = require('internal/stream'); +const debug = require('internal/debuglog')('stream'); +const inherits = require('internal/inherits'); + +var Duplex; // Break recursive dependency with _stream_duplex.js. var StringDecoder; -util.inherits(Readable, Stream); +inherits(Readable, Stream); function ReadableState(options, stream) { options = options || {}; @@ -19,7 +21,10 @@ function ReadableState(options, stream) { // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; - if (stream instanceof Stream.Duplex) + if (Duplex === undefined) + Duplex = require('_stream_duplex'); + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index 8ff428e11ffed0..70b1fcca93aa4c 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -45,8 +45,8 @@ module.exports = Transform; const Duplex = require('_stream_duplex'); -const util = require('util'); -util.inherits(Transform, Duplex); +const inherits = require('internal/inherits'); +inherits(Transform, Duplex); function TransformState(stream) { diff --git a/lib/_stream_wrap.js b/lib/_stream_wrap.js index 924d07a986a906..78e91968ad680d 100644 --- a/lib/_stream_wrap.js +++ b/lib/_stream_wrap.js @@ -1,11 +1,11 @@ 'use strict'; const assert = require('assert'); -const util = require('util'); const Socket = require('net').Socket; const JSStream = process.binding('js_stream').JSStream; const uv = process.binding('uv'); -const debug = util.debuglog('stream_wrap'); +const debug = require('internal/debuglog')('stream_wrap'); +const inherits = require('internal/inherits'); function StreamWrap(stream) { const handle = new JSStream(); @@ -57,7 +57,7 @@ function StreamWrap(stream) { handle: handle }); } -util.inherits(StreamWrap, Socket); +inherits(StreamWrap, Socket); module.exports = StreamWrap; // require('_stream_wrap').StreamWrap diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 19c0c8a006f62a..e8b6040ca463c3 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -7,12 +7,14 @@ module.exports = Writable; Writable.WritableState = WritableState; -const util = require('util'); -const internalUtil = require('internal/util'); -const Stream = require('stream'); const Buffer = require('buffer').Buffer; +const Stream = require('internal/stream'); +const inherits = require('internal/inherits'); +const internalUtil = require('internal/util'); + +inherits(Writable, Stream); -util.inherits(Writable, Stream); +var Duplex; // Break recursive dependency with _stream_duplex.js. function nop() {} @@ -30,7 +32,10 @@ function WritableState(options, stream) { // contains buffers or objects. this.objectMode = !!options.objectMode; - if (stream instanceof Stream.Duplex) + if (Duplex === undefined) + Duplex = require('_stream_duplex'); + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false @@ -130,8 +135,13 @@ Object.defineProperty(WritableState.prototype, 'buffer', { function Writable(options) { // Writable ctor is applied to Duplexes, though they're not // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) - return new Writable(options); + if (!(this instanceof Writable)) { + if (Duplex === undefined) + Duplex = require('_stream_duplex'); + + if (!(this instanceof Duplex)) + return new Writable(options); + } this._writableState = new WritableState(options, this); diff --git a/lib/console.js b/lib/console.js index f9032e24a0fa44..eb9610009c324f 100644 --- a/lib/console.js +++ b/lib/console.js @@ -1,6 +1,7 @@ 'use strict'; -const util = require('util'); +const format = require('internal/format'); + function Console(stdout, stderr) { if (!(this instanceof Console)) { @@ -33,7 +34,7 @@ function Console(stdout, stderr) { } Console.prototype.log = function() { - this._stdout.write(util.format.apply(this, arguments) + '\n'); + this._stdout.write(format.apply(this, arguments) + '\n'); }; @@ -41,15 +42,22 @@ Console.prototype.info = Console.prototype.log; Console.prototype.warn = function() { - this._stderr.write(util.format.apply(this, arguments) + '\n'); + this._stderr.write(format.apply(this, arguments) + '\n'); }; Console.prototype.error = Console.prototype.warn; +var extend; +var inspect; + Console.prototype.dir = function(object, options) { - this._stdout.write(util.inspect(object, util._extend({ + if (extend === undefined) { + extend = require('internal/extend'); + inspect = require('util').inspect; + } + this._stdout.write(inspect(object, extend({ customInspect: false }, options)) + '\n'); }; @@ -75,7 +83,7 @@ Console.prototype.trace = function trace() { // exposed. var err = new Error(); err.name = 'Trace'; - err.message = util.format.apply(this, arguments); + err.message = format.apply(this, arguments); Error.captureStackTrace(err, trace); this.error(err.stack); }; @@ -84,7 +92,7 @@ Console.prototype.trace = function trace() { Console.prototype.assert = function(expression) { if (!expression) { var arr = Array.prototype.slice.call(arguments, 1); - require('assert').ok(false, util.format.apply(this, arr)); + require('assert').ok(false, format.apply(this, arr)); } }; diff --git a/lib/dgram.js b/lib/dgram.js index b7bb7d3d703eb1..b773bdcac6c10d 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -2,10 +2,13 @@ const assert = require('assert'); const Buffer = require('buffer').Buffer; -const util = require('util'); const events = require('events'); const constants = require('constants'); +const errnoException = require('internal/errno_exception'); +const exceptionWithHostPort = require('internal/exception_with_host_port'); +const inherits = require('internal/inherits'); + const UDP = process.binding('udp_wrap').UDP; const SendWrap = process.binding('udp_wrap').SendWrap; @@ -17,9 +20,6 @@ const BIND_STATE_BOUND = 2; var cluster = null; var dns = null; -const errnoException = util._errnoException; -const exceptionWithHostPort = util._exceptionWithHostPort; - function lookup(address, family, callback) { if (!dns) dns = require('dns'); @@ -101,7 +101,7 @@ function Socket(type, listener) { if (typeof listener === 'function') this.on('message', listener); } -util.inherits(Socket, events.EventEmitter); +inherits(Socket, events.EventEmitter); exports.Socket = Socket; diff --git a/lib/fs.js b/lib/fs.js index 9bfd14cd29b512..51f983c70c61f8 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -4,7 +4,6 @@ 'use strict'; const SlowBuffer = require('buffer').SlowBuffer; -const util = require('util'); const pathModule = require('path'); const binding = process.binding('fs'); @@ -34,7 +33,9 @@ const O_WRONLY = constants.O_WRONLY || 0; const isWindows = process.platform === 'win32'; const DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); -const errnoException = util._errnoException; +const errnoException = require('internal/errno_exception'); +const extend = require('internal/extend'); +const inherits = require('internal/inherits'); function throwOptionsError(options) { throw new TypeError('Expected options to be either an object or a string, ' + @@ -1048,7 +1049,7 @@ function toUnixTimestamp(time) { if (typeof time === 'number') { return time; } - if (util.isDate(time)) { + if (Object.prototype.toString.call(time) === '[object Date]') { // convert to 123.456 UNIX timestamp return time.getTime() / 1000; } @@ -1185,7 +1186,7 @@ fs.appendFile = function(path, data, options, callback_) { } if (!options.flag) - options = util._extend({ flag: 'a' }, options); + options = extend({ flag: 'a' }, options); fs.writeFile(path, data, options, callback); }; @@ -1198,7 +1199,7 @@ fs.appendFileSync = function(path, data, options) { throwOptionsError(options); } if (!options.flag) - options = util._extend({ flag: 'a' }, options); + options = extend({ flag: 'a' }, options); fs.writeFileSync(path, data, options); }; @@ -1219,7 +1220,7 @@ function FSWatcher() { } }; } -util.inherits(FSWatcher, EventEmitter); +inherits(FSWatcher, EventEmitter); FSWatcher.prototype.start = function(filename, persistent, recursive) { nullCheck(filename); @@ -1289,7 +1290,7 @@ function StatWatcher() { self.emit('stop'); }; } -util.inherits(StatWatcher, EventEmitter); +inherits(StatWatcher, EventEmitter); StatWatcher.prototype.start = function(filename, persistent, interval) { @@ -1319,7 +1320,7 @@ fs.watchFile = function(filename, options, listener) { }; if (options !== null && typeof options === 'object') { - options = util._extend(defaults, options); + options = extend(defaults, options); } else { listener = options; options = defaults; @@ -1607,7 +1608,7 @@ fs.createReadStream = function(path, options) { return new ReadStream(path, options); }; -util.inherits(ReadStream, Readable); +inherits(ReadStream, Readable); fs.ReadStream = ReadStream; function ReadStream(path, options) { @@ -1779,7 +1780,7 @@ fs.createWriteStream = function(path, options) { return new WriteStream(path, options); }; -util.inherits(WriteStream, Writable); +inherits(WriteStream, Writable); fs.WriteStream = WriteStream; function WriteStream(path, options) { if (!(this instanceof WriteStream)) @@ -1887,7 +1888,7 @@ function SyncWriteStream(fd, options) { this.autoClose = options.autoClose === undefined ? true : options.autoClose; } -util.inherits(SyncWriteStream, Stream); +inherits(SyncWriteStream, Stream); // Export diff --git a/lib/internal/assert.js b/lib/internal/assert.js new file mode 100644 index 00000000000000..6d3923d1b6275f --- /dev/null +++ b/lib/internal/assert.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function assert(expression, message) { + if (!expression) + throw new Error(`Internal assertion failed: ${message || 'no message'}`); +}; diff --git a/lib/internal/debuglog.js b/lib/internal/debuglog.js new file mode 100644 index 00000000000000..eea204ecaf167c --- /dev/null +++ b/lib/internal/debuglog.js @@ -0,0 +1,25 @@ +'use strict'; + +const debugs = {}; +var debugEnviron; +var format; + +module.exports = function(set) { + if (debugEnviron === undefined) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + if (format === undefined) + format = require('internal/format'); + const msg = format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; diff --git a/lib/internal/errno_exception.js b/lib/internal/errno_exception.js new file mode 100644 index 00000000000000..1bd739e7c15985 --- /dev/null +++ b/lib/internal/errno_exception.js @@ -0,0 +1,17 @@ +'use strict'; + +var uv; + +module.exports = function errnoException(err, syscall, original) { + if (uv === undefined) + uv = process.binding('uv'); + var errname = uv.errname(err); + var message = syscall + ' ' + errname; + if (original) + message += ' ' + original; + var e = new Error(message); + e.code = errname; + e.errno = errname; + e.syscall = syscall; + return e; +}; diff --git a/lib/internal/exception_with_host_port.js b/lib/internal/exception_with_host_port.js new file mode 100644 index 00000000000000..67b7f3daaf24fa --- /dev/null +++ b/lib/internal/exception_with_host_port.js @@ -0,0 +1,28 @@ +'use strict'; + +var errnoException; + +module.exports = function exceptionWithHostPort(err, + syscall, + address, + port, + additional) { + var details; + if (port && port > 0) { + details = address + ':' + port; + } else { + details = address; + } + + if (additional) { + details += ' - Local (' + additional + ')'; + } + if (errnoException === undefined) + errnoException = require('internal/errno_exception'); + const ex = errnoException(err, syscall, details); + ex.address = address; + if (port) { + ex.port = port; + } + return ex; +}; diff --git a/lib/internal/extend.js b/lib/internal/extend.js new file mode 100644 index 00000000000000..d8b6f44941fffc --- /dev/null +++ b/lib/internal/extend.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function extend(origin, add) { + // Don't do anything if add isn't an object + if (add === null || typeof add !== 'object') return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; diff --git a/lib/internal/format.js b/lib/internal/format.js new file mode 100644 index 00000000000000..44a774c52fc42f --- /dev/null +++ b/lib/internal/format.js @@ -0,0 +1,50 @@ +'use strict'; + +const formatRegExp = /%[sdj%]/g; +module.exports = function format(f) { + if (typeof f !== 'string') { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + if (arguments.length === 1) return f; + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + // falls through + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + +function inspect(x) { + if (inspect.cached === undefined) + inspect.cached = require('util').inspect; + return inspect.cached(x); +} +inspect.cached = undefined; diff --git a/lib/internal/inherits.js b/lib/internal/inherits.js new file mode 100644 index 00000000000000..8e781613cd9ed4 --- /dev/null +++ b/lib/internal/inherits.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + * @throws {TypeError} Will error if either constructor is null, or if + * the super constructor lacks a prototype. + */ +module.exports = function inherits(ctor, superCtor) { + if (ctor === undefined || ctor === null) + throw new TypeError('The constructor to `inherits` must not be ' + + 'null or undefined.'); + + if (superCtor === undefined || superCtor === null) + throw new TypeError('The super constructor to `inherits` must not ' + + 'be null or undefined.'); + + if (superCtor.prototype === undefined) + throw new TypeError('The super constructor to `inherits` must ' + + 'have a prototype.'); + + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +}; diff --git a/lib/internal/stream.js b/lib/internal/stream.js new file mode 100644 index 00000000000000..541b477fe258e7 --- /dev/null +++ b/lib/internal/stream.js @@ -0,0 +1,94 @@ +'use strict'; + +module.exports = Stream; + +const EE = require('events'); +const inherits = require('internal/inherits'); + +function Stream() { + EE.call(this); +} +inherits(Stream, EE); + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; diff --git a/lib/module.js b/lib/module.js index da8a906f951541..389e386429623d 100644 --- a/lib/module.js +++ b/lib/module.js @@ -1,16 +1,23 @@ 'use strict'; const NativeModule = require('native_module'); -const util = require('util'); +const assert = require('internal/assert'); +const debug = require('internal/debuglog')('module'); const internalUtil = require('internal/util'); const runInThisContext = require('vm').runInThisContext; -const assert = require('assert').ok; -const fs = require('fs'); const path = require('path'); const internalModuleReadFile = process.binding('fs').internalModuleReadFile; const internalModuleStat = process.binding('fs').internalModuleStat; +function fs() { + if (fs.cached === undefined) + fs.cached = require('fs'); + return fs.cached; +} +fs.cached = undefined; + + // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 @@ -41,11 +48,7 @@ Module.globalPaths = []; Module.wrapper = NativeModule.wrapper; Module.wrap = NativeModule.wrap; -Module._debug = util.debuglog('module'); - - -// We use this alias for the preprocessor that filters it out -const debug = Module._debug; +Module._debug = debug; // given a module name, and a list of paths to test, returns the first @@ -106,7 +109,7 @@ function tryFile(requestPath) { } function toRealPath(requestPath) { - return fs.realpathSync(requestPath, Module._realpathCache); + return fs().realpathSync(requestPath, Module._realpathCache); } // given a path check a the file exists with any of the set extensions @@ -448,14 +451,14 @@ function stripBOM(content) { // Native extension for .js Module._extensions['.js'] = function(module, filename) { - var content = fs.readFileSync(filename, 'utf8'); + var content = fs().readFileSync(filename, 'utf8'); module._compile(stripBOM(content), filename); }; // Native extension for .json Module._extensions['.json'] = function(module, filename) { - var content = fs.readFileSync(filename, 'utf8'); + var content = fs().readFileSync(filename, 'utf8'); try { module.exports = JSON.parse(stripBOM(content)); } catch (err) { diff --git a/lib/net.js b/lib/net.js index 10e789678440fd..955536dc612d16 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1,14 +1,14 @@ 'use strict'; const events = require('events'); -const stream = require('stream'); const timers = require('timers'); -const util = require('util'); const internalUtil = require('internal/util'); -const assert = require('assert'); const cares = process.binding('cares_wrap'); const uv = process.binding('uv'); +const Duplex = require('_stream_duplex'); +const Readable = require('_stream_readable'); + const Buffer = require('buffer').Buffer; const TTYWrap = process.binding('tty_wrap'); const TCP = process.binding('tcp_wrap').TCP; @@ -18,10 +18,13 @@ const PipeConnectWrap = process.binding('pipe_wrap').PipeConnectWrap; const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; const WriteWrap = process.binding('stream_wrap').WriteWrap; +const assert = require('internal/assert'); +const debug = require('internal/debuglog')('net'); +const errnoException = require('internal/errno_exception'); +const exceptionWithHostPort = require('internal/exception_with_host_port'); +const inherits = require('internal/inherits'); var cluster; -const errnoException = util._errnoException; -const exceptionWithHostPort = util._exceptionWithHostPort; function noop() {} @@ -33,8 +36,6 @@ function createHandle(fd) { } -const debug = util.debuglog('net'); - function isPipeName(s) { return typeof s === 'string' && toNumber(s) === false; } @@ -120,7 +121,7 @@ function Socket(options) { else if (options === undefined) options = {}; - stream.Duplex.call(this, options); + Duplex.call(this, options); if (options.handle) { this._handle = options.handle; // private @@ -170,7 +171,7 @@ function Socket(options) { } } } -util.inherits(Socket, stream.Duplex); +inherits(Socket, Duplex); Socket.prototype._unrefTimer = function unrefTimer() { for (var s = this; s !== null; s = s._parent) @@ -280,9 +281,9 @@ exports.Stream = Socket; // Legacy naming. Socket.prototype.read = function(n) { if (n === 0) - return stream.Readable.prototype.read.call(this, n); + return Readable.prototype.read.call(this, n); - this.read = stream.Readable.prototype.read; + this.read = Readable.prototype.read; this._consuming = true; return this.read(n); }; @@ -397,7 +398,7 @@ Socket.prototype._read = function(n) { Socket.prototype.end = function(data, encoding) { - stream.Duplex.prototype.end.call(this, data, encoding); + Duplex.prototype.end.call(this, data, encoding); this.writable = false; DTRACE_NET_STREAM_END(this); LTTNG_NET_STREAM_END(this); @@ -615,7 +616,7 @@ Socket.prototype.__defineGetter__('localPort', function() { Socket.prototype.write = function(chunk, encoding, cb) { if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) throw new TypeError('invalid data'); - return stream.Duplex.prototype.write.apply(this, arguments); + return Duplex.prototype.write.apply(this, arguments); }; @@ -777,7 +778,7 @@ function connect(self, address, port, addressType, localAddress, localPort) { // TODO return promise from Socket.prototype.connect which // wraps _connectReq. - assert.ok(self._connecting); + assert(self._connecting); var err; @@ -1033,7 +1034,7 @@ function afterConnect(status, handle, req, readable, writable) { debug('afterConnect'); - assert.ok(self._connecting); + assert(self._connecting); self._connecting = false; self._sockname = null; @@ -1113,7 +1114,7 @@ function Server(options, connectionListener) { this.allowHalfOpen = options.allowHalfOpen || false; this.pauseOnConnect = !!options.pauseOnConnect; } -util.inherits(Server, events.EventEmitter); +inherits(Server, events.EventEmitter); exports.Server = Server; diff --git a/lib/path.js b/lib/path.js index 4bcb2b3672091c..42be8a7b790d42 100644 --- a/lib/path.js +++ b/lib/path.js @@ -1,12 +1,11 @@ 'use strict'; -const util = require('util'); const isWindows = process.platform === 'win32'; function assertPath(path) { if (typeof path !== 'string') { throw new TypeError('Path must be a string. Received ' + - util.inspect(path)); + require('util').inspect(path)); } } diff --git a/lib/stream.js b/lib/stream.js index 8d3535dc4d2f0e..4030b3de542478 100644 --- a/lib/stream.js +++ b/lib/stream.js @@ -1,11 +1,10 @@ 'use strict'; -module.exports = Stream; +const Stream = require('internal/stream'); +const inherits = require('internal/inherits'); -const EE = require('events').EventEmitter; -const util = require('util'); +module.exports = Stream; -util.inherits(Stream, EE); Stream.Readable = require('_stream_readable'); Stream.Writable = require('_stream_writable'); Stream.Duplex = require('_stream_duplex'); @@ -14,94 +13,3 @@ Stream.PassThrough = require('_stream_passthrough'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; diff --git a/lib/timers.js b/lib/timers.js index e3d0eb152490f9..04d2371921be7a 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -2,9 +2,8 @@ const Timer = process.binding('timer_wrap').Timer; const L = require('_linklist'); -const assert = require('assert').ok; -const util = require('util'); -const debug = util.debuglog('timer'); +const assert = require('internal/assert'); +const debug = require('internal/debuglog')('timer'); const kOnTimeout = Timer.kOnTimeout | 0; // Timeout values > TIMEOUT_MAX are set to 1. diff --git a/lib/tty.js b/lib/tty.js index f3f84ca5a6e9f7..2a000cd1ad9d72 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -1,12 +1,11 @@ 'use strict'; -const util = require('util'); const internalUtil = require('internal/util'); const net = require('net'); const TTY = process.binding('tty_wrap').TTY; const isTTY = process.binding('tty_wrap').isTTY; -const inherits = util.inherits; -const errnoException = util._errnoException; +const extend = require('internal/extend'); +const inherits = require('internal/inherits'); exports.isatty = function(fd) { @@ -28,7 +27,7 @@ function ReadStream(fd, options) { if (!(this instanceof ReadStream)) return new ReadStream(fd, options); - options = util._extend({ + options = extend({ highWaterMark: 0, readable: true, writable: false, @@ -79,6 +78,7 @@ WriteStream.prototype._refreshSize = function() { var winSize = []; var err = this._handle.getWindowSize(winSize); if (err) { + const errnoException = require('internal/errno_exception'); this.emit('error', errnoException(err, 'getWindowSize')); return; } diff --git a/lib/util.js b/lib/util.js index c5d7bea7db352d..8854a665ac4458 100644 --- a/lib/util.js +++ b/lib/util.js @@ -1,75 +1,12 @@ 'use strict'; -const uv = process.binding('uv'); const Buffer = require('buffer').Buffer; const internalUtil = require('internal/util'); var Debug; -const formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (typeof f !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - if (arguments.length === 1) return f; - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - // falls through - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - +exports.debuglog = require('internal/debuglog'); exports.deprecate = internalUtil._deprecate; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (debugEnviron === undefined) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; +exports.format = require('internal/format'); /** @@ -694,57 +631,9 @@ exports.log = function() { }; -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - * @throws {TypeError} Will error if either constructor is null, or if - * the super constructor lacks a prototype. - */ -exports.inherits = function(ctor, superCtor) { - - if (ctor === undefined || ctor === null) - throw new TypeError('The constructor to `inherits` must not be ' + - 'null or undefined.'); - - if (superCtor === undefined || superCtor === null) - throw new TypeError('The super constructor to `inherits` must not ' + - 'be null or undefined.'); - - if (superCtor.prototype === undefined) - throw new TypeError('The super constructor to `inherits` must ' + - 'have a prototype.'); - - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -}; - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (add === null || typeof add !== 'object') return origin; +exports._extend = require('internal/extend'); +exports.inherits = require('internal/inherits'); - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); @@ -829,38 +718,6 @@ exports.pump = internalUtil.deprecate(function(readStream, writeStream, cb) { }, 'util.pump is deprecated. Use readableStream.pipe instead.'); -exports._errnoException = function(err, syscall, original) { - var errname = uv.errname(err); - var message = syscall + ' ' + errname; - if (original) - message += ' ' + original; - var e = new Error(message); - e.code = errname; - e.errno = errname; - e.syscall = syscall; - return e; -}; - - -exports._exceptionWithHostPort = function(err, - syscall, - address, - port, - additional) { - var details; - if (port && port > 0) { - details = address + ':' + port; - } else { - details = address; - } - - if (additional) { - details += ' - Local (' + additional + ')'; - } - var ex = exports._errnoException(err, syscall, details); - ex.address = address; - if (port) { - ex.port = port; - } - return ex; -}; +// XXX(bnoordhuis) I think these can just be removed. +exports._errnoException = require('internal/errno_exception'); +exports._exceptionWithHostPort = require('internal/exception_with_host_port'); diff --git a/node.gyp b/node.gyp index 0bc27ae4f63b16..85cc51a41921b2 100644 --- a/node.gyp +++ b/node.gyp @@ -68,10 +68,18 @@ 'lib/v8.js', 'lib/vm.js', 'lib/zlib.js', + 'lib/internal/assert.js', 'lib/internal/child_process.js', + 'lib/internal/debuglog.js', + 'lib/internal/errno_exception.js', + 'lib/internal/exception_with_host_port.js', + 'lib/internal/extend.js', 'lib/internal/freelist.js', - 'lib/internal/socket_list.js', + 'lib/internal/format.js', + 'lib/internal/inherits.js', 'lib/internal/repl.js', + 'lib/internal/socket_list.js', + 'lib/internal/stream.js', 'lib/internal/util.js', ], }, diff --git a/src/node.js b/src/node.js index bd91fb888ae046..03a91f759f5a90 100644 --- a/src/node.js +++ b/src/node.js @@ -834,9 +834,11 @@ startup.processRawDebug = function() { - var format = NativeModule.require('util').format; + var format; var rawDebug = process._rawDebug; process._rawDebug = function() { + if (format === undefined) + format = NativeModule.require('util').format; rawDebug(format.apply(null, arguments)); }; };