3 const uv = process.binding('uv');
5 const formatRegExp = /%[sdj%]/g;
6 exports.format = function(f) {
7 if (typeof f !== 'string') {
9 for (var i = 0; i < arguments.length; i++) {
10 objects.push(inspect(arguments[i]));
12 return objects.join(' ');
17 var len = args.length;
18 var str = String(f).replace(formatRegExp, function(x) {
19 if (x === '%%') return '%';
20 if (i >= len) return x;
22 case '%s': return String(args[i++]);
23 case '%d': return Number(args[i++]);
26 return JSON.stringify(args[i++]);
34 for (var x = args[i]; i < len; x = args[++i]) {
35 if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) {
38 str += ' ' + inspect(x);
45 // Mark that a method should not be used.
46 // Returns a modified function which warns once by default.
47 // If --no-deprecation is set, then it is a no-op.
48 exports.deprecate = function(fn, msg) {
49 // Allow for deprecating things in the process of starting up.
50 if (global.process === undefined) {
52 return exports.deprecate(fn, msg).apply(this, arguments);
56 if (process.noDeprecation === true) {
61 function deprecated() {
63 if (process.throwDeprecation) {
65 } else if (process.traceDeprecation) {
72 return fn.apply(this, arguments);
81 exports.debuglog = function(set) {
82 if (debugEnviron === undefined)
83 debugEnviron = process.env.NODE_DEBUG || '';
84 set = set.toUpperCase();
86 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
87 var pid = process.pid;
88 debugs[set] = function() {
89 var msg = exports.format.apply(exports, arguments);
90 console.error('%s %d: %s', set, pid, msg);
93 debugs[set] = function() {};
101 * Echos the value of a value. Trys to print the value out
102 * in the best way possible given the different types.
104 * @param {Object} obj The object to print out.
105 * @param {Object} opts Optional options object that alters the output.
107 /* legacy: obj, showHidden, depth, colors*/
108 function inspect(obj, opts) {
112 stylize: stylizeNoColor
115 if (arguments.length >= 3) ctx.depth = arguments[2];
116 if (arguments.length >= 4) ctx.colors = arguments[3];
117 if (typeof opts === 'boolean') {
119 ctx.showHidden = opts;
121 // got an "options" object
122 exports._extend(ctx, opts);
124 // set default options
125 if (ctx.showHidden === undefined) ctx.showHidden = false;
126 if (ctx.depth === undefined) ctx.depth = 2;
127 if (ctx.colors === undefined) ctx.colors = false;
128 if (ctx.customInspect === undefined) ctx.customInspect = true;
129 if (ctx.colors) ctx.stylize = stylizeWithColor;
130 return formatValue(ctx, obj, ctx.depth);
132 exports.inspect = inspect;
135 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
139 'underline' : [4, 24],
147 'magenta' : [35, 39],
152 // Don't use 'blue' not visible on cmd.exe
162 // "name": intentionally not styling
167 function stylizeWithColor(str, styleType) {
168 var style = inspect.styles[styleType];
171 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
172 '\u001b[' + inspect.colors[style][1] + 'm';
179 function stylizeNoColor(str, styleType) {
184 function arrayToHash(array) {
187 array.forEach(function(val, idx) {
195 function formatValue(ctx, value, recurseTimes) {
196 // Provide a hook for user-specified inspect functions.
197 // Check that value is an object with an inspect function on it
198 if (ctx.customInspect &&
200 typeof value.inspect === 'function' &&
201 // Filter out the util module, it's inspect function is special
202 value.inspect !== exports.inspect &&
203 // Also filter out any prototype objects using the circular check.
204 !(value.constructor && value.constructor.prototype === value)) {
205 var ret = value.inspect(recurseTimes, ctx);
206 if (typeof ret !== 'string') {
207 ret = formatValue(ctx, ret, recurseTimes);
212 // Primitive types cannot have properties
213 var primitive = formatPrimitive(ctx, value);
218 // Look up the keys of the object.
219 var keys = Object.keys(value);
220 var visibleKeys = arrayToHash(keys);
222 if (ctx.showHidden) {
223 keys = Object.getOwnPropertyNames(value);
224 keys = keys.concat(Object.getOwnPropertySymbols(value));
227 // This could be a boxed primitive (new String(), etc.), check valueOf()
228 // NOTE: Avoid calling `valueOf` on `Date` instance because it will return
229 // a number which, when object has some additional user-stored `keys`,
230 // will be printed out.
234 // the .valueOf() call can fail for a multitude of reasons
236 raw = value.valueOf();
241 if (typeof raw === 'string') {
242 // for boxed Strings, we have to remove the 0-n indexed entries,
243 // since they just noisey up the output and are redundant
244 keys = keys.filter(function(key) {
245 return !(key >= 0 && key < raw.length);
249 // Some type of object without properties can be shortcutted.
250 if (keys.length === 0) {
251 if (typeof value === 'function') {
252 var name = value.name ? ': ' + value.name : '';
253 return ctx.stylize('[Function' + name + ']', 'special');
255 if (isRegExp(value)) {
256 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
259 return ctx.stylize(Date.prototype.toString.call(value), 'date');
261 if (isError(value)) {
262 return formatError(value);
264 // now check the `raw` value to handle boxed primitives
265 if (typeof raw === 'string') {
266 formatted = formatPrimitiveNoColor(ctx, raw);
267 return ctx.stylize('[String: ' + formatted + ']', 'string');
269 if (typeof raw === 'number') {
270 formatted = formatPrimitiveNoColor(ctx, raw);
271 return ctx.stylize('[Number: ' + formatted + ']', 'number');
273 if (typeof raw === 'boolean') {
274 formatted = formatPrimitiveNoColor(ctx, raw);
275 return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
279 var base = '', array = false, braces = ['{', '}'];
281 // Make Array say that they are Array
282 if (Array.isArray(value)) {
287 // Make functions say that they are functions
288 if (typeof value === 'function') {
289 var n = value.name ? ': ' + value.name : '';
290 base = ' [Function' + n + ']';
293 // Make RegExps say that they are RegExps
294 if (isRegExp(value)) {
295 base = ' ' + RegExp.prototype.toString.call(value);
298 // Make dates with properties first say the date
300 base = ' ' + Date.prototype.toUTCString.call(value);
303 // Make error with message first say the error
304 if (isError(value)) {
305 base = ' ' + formatError(value);
308 // Make boxed primitive Strings look like such
309 if (typeof raw === 'string') {
310 formatted = formatPrimitiveNoColor(ctx, raw);
311 base = ' ' + '[String: ' + formatted + ']';
314 // Make boxed primitive Numbers look like such
315 if (typeof raw === 'number') {
316 formatted = formatPrimitiveNoColor(ctx, raw);
317 base = ' ' + '[Number: ' + formatted + ']';
320 // Make boxed primitive Booleans look like such
321 if (typeof raw === 'boolean') {
322 formatted = formatPrimitiveNoColor(ctx, raw);
323 base = ' ' + '[Boolean: ' + formatted + ']';
326 if (keys.length === 0 && (!array || value.length === 0)) {
327 return braces[0] + base + braces[1];
330 if (recurseTimes < 0) {
331 if (isRegExp(value)) {
332 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
334 return ctx.stylize('[Object]', 'special');
338 ctx.seen.push(value);
342 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
344 output = keys.map(function(key) {
345 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
351 return reduceToSingleString(output, base, braces);
355 function formatPrimitive(ctx, value) {
356 if (value === undefined)
357 return ctx.stylize('undefined', 'undefined');
359 // For some reason typeof null is "object", so special case here.
361 return ctx.stylize('null', 'null');
363 var type = typeof value;
365 if (type === 'string') {
366 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
367 .replace(/'/g, "\\'")
368 .replace(/\\"/g, '"') + '\'';
369 return ctx.stylize(simple, 'string');
371 if (type === 'number') {
372 // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
373 // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
374 if (value === 0 && 1 / value < 0)
375 return ctx.stylize('-0', 'number');
376 return ctx.stylize('' + value, 'number');
378 if (type === 'boolean')
379 return ctx.stylize('' + value, 'boolean');
380 // es6 symbol primitive
381 if (type === 'symbol')
382 return ctx.stylize(value.toString(), 'symbol');
386 function formatPrimitiveNoColor(ctx, value) {
387 var stylize = ctx.stylize;
388 ctx.stylize = stylizeNoColor;
389 var str = formatPrimitive(ctx, value);
390 ctx.stylize = stylize;
395 function formatError(value) {
396 return '[' + Error.prototype.toString.call(value) + ']';
400 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
402 for (var i = 0, l = value.length; i < l; ++i) {
403 if (hasOwnProperty(value, String(i))) {
404 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
410 keys.forEach(function(key) {
411 if (typeof key === 'symbol' || !key.match(/^\d+$/)) {
412 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
420 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
422 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
425 str = ctx.stylize('[Getter/Setter]', 'special');
427 str = ctx.stylize('[Getter]', 'special');
431 str = ctx.stylize('[Setter]', 'special');
434 if (!hasOwnProperty(visibleKeys, key)) {
435 if (typeof key === 'symbol') {
436 name = '[' + ctx.stylize(key.toString(), 'symbol') + ']';
438 name = '[' + key + ']';
442 if (ctx.seen.indexOf(desc.value) < 0) {
443 if (recurseTimes === null) {
444 str = formatValue(ctx, desc.value, null);
446 str = formatValue(ctx, desc.value, recurseTimes - 1);
448 if (str.indexOf('\n') > -1) {
450 str = str.split('\n').map(function(line) {
452 }).join('\n').substr(2);
454 str = '\n' + str.split('\n').map(function(line) {
460 str = ctx.stylize('[Circular]', 'special');
463 if (name === undefined) {
464 if (array && key.match(/^\d+$/)) {
467 name = JSON.stringify('' + key);
468 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
469 name = name.substr(1, name.length - 2);
470 name = ctx.stylize(name, 'name');
472 name = name.replace(/'/g, "\\'")
473 .replace(/\\"/g, '"')
474 .replace(/(^"|"$)/g, "'")
475 .replace(/\\\\/g, '\\');
476 name = ctx.stylize(name, 'string');
480 return name + ': ' + str;
484 function reduceToSingleString(output, base, braces) {
485 var length = output.reduce(function(prev, cur) {
486 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
491 (base === '' ? '' : base + '\n ') +
493 output.join(',\n ') +
498 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
502 // NOTE: These type checking functions intentionally don't use `instanceof`
503 // because it is fragile and can be easily faked with `Object.create()`.
504 exports.isArray = Array.isArray;
506 function isBoolean(arg) {
507 return typeof arg === 'boolean';
509 exports.isBoolean = isBoolean;
511 function isNull(arg) {
514 exports.isNull = isNull;
516 function isNullOrUndefined(arg) {
517 return arg === null || arg === undefined;
519 exports.isNullOrUndefined = isNullOrUndefined;
521 function isNumber(arg) {
522 return typeof arg === 'number';
524 exports.isNumber = isNumber;
526 function isString(arg) {
527 return typeof arg === 'string';
529 exports.isString = isString;
531 function isSymbol(arg) {
532 return typeof arg === 'symbol';
534 exports.isSymbol = isSymbol;
536 function isUndefined(arg) {
537 return arg === undefined;
539 exports.isUndefined = isUndefined;
541 function isRegExp(re) {
542 return re !== null && typeof re === 'object' &&
543 objectToString(re) === '[object RegExp]';
545 exports.isRegExp = isRegExp;
547 function isObject(arg) {
548 return arg !== null && typeof arg === 'object';
550 exports.isObject = isObject;
553 return d !== null && typeof d === 'object' &&
554 objectToString(d) === '[object Date]';
556 exports.isDate = isDate;
558 function isError(e) {
559 return e !== null && typeof e === 'object' &&
560 (objectToString(e) === '[object Error]' || e instanceof Error);
562 exports.isError = isError;
564 function isFunction(arg) {
565 return typeof arg === 'function';
567 exports.isFunction = isFunction;
569 function isPrimitive(arg) {
570 return arg === null ||
571 typeof arg !== 'object' && typeof arg !== 'function';
573 exports.isPrimitive = isPrimitive;
575 function isBuffer(arg) {
576 return arg instanceof Buffer;
578 exports.isBuffer = isBuffer;
580 function objectToString(o) {
581 return Object.prototype.toString.call(o);
586 return n < 10 ? '0' + n.toString(10) : n.toString(10);
590 const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
591 'Oct', 'Nov', 'Dec'];
594 function timestamp() {
596 var time = [pad(d.getHours()),
598 pad(d.getSeconds())].join(':');
599 return [d.getDate(), months[d.getMonth()], time].join(' ');
603 // log is just a thin wrapper to console.log that prepends a timestamp
604 exports.log = function() {
605 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
610 * Inherit the prototype methods from one constructor into another.
612 * The Function.prototype.inherits from lang.js rewritten as a standalone
613 * function (not on Function.prototype). NOTE: If this file is to be loaded
614 * during bootstrapping this function needs to be rewritten using some native
615 * functions as prototype setup using normal JavaScript does not work as
616 * expected during bootstrapping (see mirror.js in r114903).
618 * @param {function} ctor Constructor function which needs to inherit the
620 * @param {function} superCtor Constructor function to inherit prototype from.
621 * @throws {TypeError} Will error if either constructor is null, or if
622 * the super constructor lacks a prototype.
624 exports.inherits = function(ctor, superCtor) {
626 if (ctor === undefined || ctor === null)
627 throw new TypeError('The constructor to `inherits` must not be ' +
628 'null or undefined.');
630 if (superCtor === undefined || superCtor === null)
631 throw new TypeError('The super constructor to `inherits` must not ' +
632 'be null or undefined.');
634 if (superCtor.prototype === undefined)
635 throw new TypeError('The super constructor to `inherits` must ' +
636 'have a prototype.');
638 ctor.super_ = superCtor;
639 ctor.prototype = Object.create(superCtor.prototype, {
649 exports._extend = function(origin, add) {
650 // Don't do anything if add isn't an object
651 if (add === null || typeof add !== 'object') return origin;
653 var keys = Object.keys(add);
656 origin[keys[i]] = add[keys[i]];
661 function hasOwnProperty(obj, prop) {
662 return Object.prototype.hasOwnProperty.call(obj, prop);
666 // Deprecated old stuff.
668 exports.p = exports.deprecate(function() {
669 for (var i = 0, len = arguments.length; i < len; ++i) {
670 console.error(exports.inspect(arguments[i]));
672 }, 'util.p: Use console.error() instead');
675 exports.exec = exports.deprecate(function() {
676 return require('child_process').exec.apply(this, arguments);
677 }, 'util.exec is now called `child_process.exec`.');
680 exports.print = exports.deprecate(function() {
681 for (var i = 0, len = arguments.length; i < len; ++i) {
682 process.stdout.write(String(arguments[i]));
684 }, 'util.print: Use console.log instead');
687 exports.puts = exports.deprecate(function() {
688 for (var i = 0, len = arguments.length; i < len; ++i) {
689 process.stdout.write(arguments[i] + '\n');
691 }, 'util.puts: Use console.log instead');
694 exports.debug = exports.deprecate(function(x) {
695 process.stderr.write('DEBUG: ' + x + '\n');
696 }, 'util.debug: Use console.error instead');
699 exports.error = exports.deprecate(function(x) {
700 for (var i = 0, len = arguments.length; i < len; ++i) {
701 process.stderr.write(arguments[i] + '\n');
703 }, 'util.error: Use console.error instead');
706 exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
707 var callbackCalled = false;
709 function call(a, b, c) {
710 if (callback && !callbackCalled) {
712 callbackCalled = true;
716 readStream.addListener('data', function(chunk) {
717 if (writeStream.write(chunk) === false) readStream.pause();
720 writeStream.addListener('drain', function() {
724 readStream.addListener('end', function() {
728 readStream.addListener('close', function() {
732 readStream.addListener('error', function(err) {
737 writeStream.addListener('error', function(err) {
738 readStream.destroy();
741 }, 'util.pump(): Use readableStream.pipe() instead');
744 exports._errnoException = function(err, syscall, original) {
745 var errname = uv.errname(err);
746 var message = syscall + ' ' + errname;
748 message += ' ' + original;
749 var e = new Error(message);
757 exports._exceptionWithHostPort = function(err,
763 if (port && port > 0) {
764 details = address + ':' + port;
770 details += ' - Local (' + additional + ')';
772 var ex = exports._errnoException(err, syscall, details);
773 ex.address = address;