3 const uv = process.binding('uv');
4 const Buffer = require('buffer').Buffer;
5 const internalUtil = require('internal/util');
6 const binding = process.binding('util');
10 const formatRegExp = /%[sdj%]/g;
11 exports.format = function(f) {
12 if (typeof f !== 'string') {
14 for (var i = 0; i < arguments.length; i++) {
15 objects.push(inspect(arguments[i]));
17 return objects.join(' ');
20 if (arguments.length === 1) return f;
24 var len = args.length;
25 var str = String(f).replace(formatRegExp, function(x) {
26 if (x === '%%') return '%';
27 if (i >= len) return x;
29 case '%s': return String(args[i++]);
30 case '%d': return Number(args[i++]);
33 return JSON.stringify(args[i++]);
42 for (var x = args[i]; i < len; x = args[++i]) {
43 if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) {
46 str += ' ' + inspect(x);
53 exports.deprecate = internalUtil._deprecate;
58 exports.debuglog = function(set) {
59 if (debugEnviron === undefined)
60 debugEnviron = process.env.NODE_DEBUG || '';
61 set = set.toUpperCase();
63 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
64 var pid = process.pid;
65 debugs[set] = function() {
66 var msg = exports.format.apply(exports, arguments);
67 console.error('%s %d: %s', set, pid, msg);
70 debugs[set] = function() {};
78 * Echos the value of a value. Trys to print the value out
79 * in the best way possible given the different types.
81 * @param {Object} obj The object to print out.
82 * @param {Object} opts Optional options object that alters the output.
84 /* legacy: obj, showHidden, depth, colors*/
85 function inspect(obj, opts) {
89 stylize: stylizeNoColor
92 if (arguments.length >= 3) ctx.depth = arguments[2];
93 if (arguments.length >= 4) ctx.colors = arguments[3];
94 if (typeof opts === 'boolean') {
96 ctx.showHidden = opts;
98 // got an "options" object
99 exports._extend(ctx, opts);
101 // set default options
102 if (ctx.showHidden === undefined) ctx.showHidden = false;
103 if (ctx.depth === undefined) ctx.depth = 2;
104 if (ctx.colors === undefined) ctx.colors = false;
105 if (ctx.customInspect === undefined) ctx.customInspect = true;
106 if (ctx.colors) ctx.stylize = stylizeWithColor;
107 return formatValue(ctx, obj, ctx.depth);
109 exports.inspect = inspect;
112 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
116 'underline' : [4, 24],
124 'magenta' : [35, 39],
129 // Don't use 'blue' not visible on cmd.exe
139 // "name": intentionally not styling
144 function stylizeWithColor(str, styleType) {
145 var style = inspect.styles[styleType];
148 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
149 '\u001b[' + inspect.colors[style][1] + 'm';
156 function stylizeNoColor(str, styleType) {
161 function arrayToHash(array) {
164 array.forEach(function(val, idx) {
172 function getConstructorOf(obj) {
174 var descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
175 if (descriptor !== undefined &&
176 typeof descriptor.value === 'function' &&
177 descriptor.value.name !== '') {
178 return descriptor.value;
181 obj = Object.getPrototypeOf(obj);
188 function ensureDebugIsInitialized() {
189 if (Debug === undefined) {
190 const runInDebugContext = require('vm').runInDebugContext;
191 Debug = runInDebugContext('Debug');
196 function inspectPromise(p) {
197 ensureDebugIsInitialized();
198 // Only create a mirror if the object is a Promise.
199 if (!binding.isPromise(p))
201 const mirror = Debug.MakeMirror(p, true);
202 return {status: mirror.status(), value: mirror.promiseValue().value_};
206 function formatValue(ctx, value, recurseTimes) {
207 // Provide a hook for user-specified inspect functions.
208 // Check that value is an object with an inspect function on it
209 if (ctx.customInspect &&
211 typeof value.inspect === 'function' &&
212 // Filter out the util module, it's inspect function is special
213 value.inspect !== exports.inspect &&
214 // Also filter out any prototype objects using the circular check.
215 !(value.constructor && value.constructor.prototype === value)) {
216 var ret = value.inspect(recurseTimes, ctx);
217 if (typeof ret !== 'string') {
218 ret = formatValue(ctx, ret, recurseTimes);
223 // Primitive types cannot have properties
224 var primitive = formatPrimitive(ctx, value);
229 // Look up the keys of the object.
230 var keys = Object.keys(value);
231 var visibleKeys = arrayToHash(keys);
233 if (ctx.showHidden) {
234 keys = Object.getOwnPropertyNames(value);
235 keys = keys.concat(Object.getOwnPropertySymbols(value));
238 // This could be a boxed primitive (new String(), etc.), check valueOf()
239 // NOTE: Avoid calling `valueOf` on `Date` instance because it will return
240 // a number which, when object has some additional user-stored `keys`,
241 // will be printed out.
245 // the .valueOf() call can fail for a multitude of reasons
247 raw = value.valueOf();
252 if (typeof raw === 'string') {
253 // for boxed Strings, we have to remove the 0-n indexed entries,
254 // since they just noisey up the output and are redundant
255 keys = keys.filter(function(key) {
256 return !(key >= 0 && key < raw.length);
260 // Some type of object without properties can be shortcutted.
261 if (keys.length === 0) {
262 if (typeof value === 'function') {
263 var name = value.name ? ': ' + value.name : '';
264 return ctx.stylize('[Function' + name + ']', 'special');
266 if (isRegExp(value)) {
267 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
270 return ctx.stylize(Date.prototype.toString.call(value), 'date');
272 if (isError(value)) {
273 return formatError(value);
275 // now check the `raw` value to handle boxed primitives
276 if (typeof raw === 'string') {
277 formatted = formatPrimitiveNoColor(ctx, raw);
278 return ctx.stylize('[String: ' + formatted + ']', 'string');
280 if (typeof raw === 'number') {
281 formatted = formatPrimitiveNoColor(ctx, raw);
282 return ctx.stylize('[Number: ' + formatted + ']', 'number');
284 if (typeof raw === 'boolean') {
285 formatted = formatPrimitiveNoColor(ctx, raw);
286 return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
290 var constructor = getConstructorOf(value);
291 var base = '', empty = false, braces, formatter;
293 // We can't compare constructors for various objects using a comparison like
294 // `constructor === Array` because the object could have come from a different
295 // context and thus the constructor won't match. Instead we check the
296 // constructor names (including those up the prototype chain where needed) to
297 // determine object types.
298 if (Array.isArray(value)) {
299 // Unset the constructor to prevent "Array [...]" for ordinary arrays.
300 if (constructor && constructor.name === 'Array')
303 empty = value.length === 0;
304 formatter = formatArray;
305 } else if (objectToString(value) === '[object Set]') {
307 // With `showHidden`, `length` will display as a hidden property for
308 // arrays. For consistency's sake, do the same for `size`, even though this
309 // property isn't selected by Object.getOwnPropertyNames().
311 keys.unshift('size');
312 empty = value.size === 0;
313 formatter = formatSet;
314 } else if (objectToString(value) === '[object Map]') {
318 keys.unshift('size');
319 empty = value.size === 0;
320 formatter = formatMap;
322 var promiseInternals = inspectPromise(value);
323 if (promiseInternals) {
325 formatter = formatPromise;
327 if (binding.isMapIterator(value)) {
328 constructor = { name: 'MapIterator' };
331 formatter = formatCollectionIterator;
332 } else if (binding.isSetIterator(value)) {
333 constructor = { name: 'SetIterator' };
336 formatter = formatCollectionIterator;
338 // Unset the constructor to prevent "Object {...}" for ordinary objects.
339 if (constructor && constructor.name === 'Object')
342 empty = true; // No other data than keys.
343 formatter = formatObject;
348 empty = empty === true && keys.length === 0;
350 // Make functions say that they are functions
351 if (typeof value === 'function') {
352 var n = value.name ? ': ' + value.name : '';
353 base = ' [Function' + n + ']';
356 // Make RegExps say that they are RegExps
357 if (isRegExp(value)) {
358 base = ' ' + RegExp.prototype.toString.call(value);
361 // Make dates with properties first say the date
363 base = ' ' + Date.prototype.toUTCString.call(value);
366 // Make error with message first say the error
367 if (isError(value)) {
368 base = ' ' + formatError(value);
371 // Make boxed primitive Strings look like such
372 if (typeof raw === 'string') {
373 formatted = formatPrimitiveNoColor(ctx, raw);
374 base = ' ' + '[String: ' + formatted + ']';
377 // Make boxed primitive Numbers look like such
378 if (typeof raw === 'number') {
379 formatted = formatPrimitiveNoColor(ctx, raw);
380 base = ' ' + '[Number: ' + formatted + ']';
383 // Make boxed primitive Booleans look like such
384 if (typeof raw === 'boolean') {
385 formatted = formatPrimitiveNoColor(ctx, raw);
386 base = ' ' + '[Boolean: ' + formatted + ']';
389 // Add constructor name if available
390 if (base === '' && constructor)
391 braces[0] = constructor.name + ' ' + braces[0];
393 if (empty === true) {
394 return braces[0] + base + braces[1];
397 if (recurseTimes < 0) {
398 if (isRegExp(value)) {
399 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
401 return ctx.stylize('[Object]', 'special');
405 ctx.seen.push(value);
407 var output = formatter(ctx, value, recurseTimes, visibleKeys, keys);
411 return reduceToSingleString(output, base, braces);
415 function formatPrimitive(ctx, value) {
416 if (value === undefined)
417 return ctx.stylize('undefined', 'undefined');
419 // For some reason typeof null is "object", so special case here.
421 return ctx.stylize('null', 'null');
423 var type = typeof value;
425 if (type === 'string') {
426 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
427 .replace(/'/g, "\\'")
428 .replace(/\\"/g, '"') + '\'';
429 return ctx.stylize(simple, 'string');
431 if (type === 'number') {
432 // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
433 // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
434 if (value === 0 && 1 / value < 0)
435 return ctx.stylize('-0', 'number');
436 return ctx.stylize('' + value, 'number');
438 if (type === 'boolean')
439 return ctx.stylize('' + value, 'boolean');
440 // es6 symbol primitive
441 if (type === 'symbol')
442 return ctx.stylize(value.toString(), 'symbol');
446 function formatPrimitiveNoColor(ctx, value) {
447 var stylize = ctx.stylize;
448 ctx.stylize = stylizeNoColor;
449 var str = formatPrimitive(ctx, value);
450 ctx.stylize = stylize;
455 function formatError(value) {
456 return '[' + Error.prototype.toString.call(value) + ']';
460 function formatObject(ctx, value, recurseTimes, visibleKeys, keys) {
461 return keys.map(function(key) {
462 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, false);
467 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
469 for (var i = 0, l = value.length; i < l; ++i) {
470 if (hasOwnProperty(value, String(i))) {
471 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
477 keys.forEach(function(key) {
478 if (typeof key === 'symbol' || !key.match(/^\d+$/)) {
479 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
487 function formatSet(ctx, value, recurseTimes, visibleKeys, keys) {
489 value.forEach(function(v) {
490 var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1;
491 var str = formatValue(ctx, v, nextRecurseTimes);
494 keys.forEach(function(key) {
495 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
502 function formatMap(ctx, value, recurseTimes, visibleKeys, keys) {
504 value.forEach(function(v, k) {
505 var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1;
506 var str = formatValue(ctx, k, nextRecurseTimes);
508 str += formatValue(ctx, v, nextRecurseTimes);
511 keys.forEach(function(key) {
512 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
518 function formatCollectionIterator(ctx, value, recurseTimes, visibleKeys, keys) {
519 ensureDebugIsInitialized();
520 const mirror = Debug.MakeMirror(value, true);
521 var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1;
522 var vals = mirror.preview();
524 for (const o of vals) {
525 output.push(formatValue(ctx, o, nextRecurseTimes));
530 function formatPromise(ctx, value, recurseTimes, visibleKeys, keys) {
532 var internals = inspectPromise(value);
533 if (internals.status === 'pending') {
534 output.push('<pending>');
536 var nextRecurseTimes = recurseTimes === null ? null : recurseTimes - 1;
537 var str = formatValue(ctx, internals.value, nextRecurseTimes);
538 if (internals.status === 'rejected') {
539 output.push('<rejected> ' + str);
544 keys.forEach(function(key) {
545 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
552 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
554 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
557 str = ctx.stylize('[Getter/Setter]', 'special');
559 str = ctx.stylize('[Getter]', 'special');
563 str = ctx.stylize('[Setter]', 'special');
566 if (!hasOwnProperty(visibleKeys, key)) {
567 if (typeof key === 'symbol') {
568 name = '[' + ctx.stylize(key.toString(), 'symbol') + ']';
570 name = '[' + key + ']';
574 if (ctx.seen.indexOf(desc.value) < 0) {
575 if (recurseTimes === null) {
576 str = formatValue(ctx, desc.value, null);
578 str = formatValue(ctx, desc.value, recurseTimes - 1);
580 if (str.indexOf('\n') > -1) {
582 str = str.replace(/\n/g, '\n ');
584 str = str.replace(/(^|\n)/g, '\n ');
588 str = ctx.stylize('[Circular]', 'special');
591 if (name === undefined) {
592 if (array && key.match(/^\d+$/)) {
595 name = JSON.stringify('' + key);
596 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
597 name = name.substr(1, name.length - 2);
598 name = ctx.stylize(name, 'name');
600 name = name.replace(/'/g, "\\'")
601 .replace(/\\"/g, '"')
602 .replace(/(^"|"$)/g, "'")
603 .replace(/\\\\/g, '\\');
604 name = ctx.stylize(name, 'string');
608 return name + ': ' + str;
612 function reduceToSingleString(output, base, braces) {
613 var length = output.reduce(function(prev, cur) {
614 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
619 // If the opening "brace" is too large, like in the case of "Set {",
620 // we need to force the first item to be on the next line or the
621 // items will not line up correctly.
622 (base === '' && braces[0].length === 1 ? '' : base + '\n ') +
624 output.join(',\n ') +
629 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
633 // NOTE: These type checking functions intentionally don't use `instanceof`
634 // because it is fragile and can be easily faked with `Object.create()`.
635 exports.isArray = Array.isArray;
637 function isBoolean(arg) {
638 return typeof arg === 'boolean';
640 exports.isBoolean = isBoolean;
642 function isNull(arg) {
645 exports.isNull = isNull;
647 function isNullOrUndefined(arg) {
648 return arg === null || arg === undefined;
650 exports.isNullOrUndefined = isNullOrUndefined;
652 function isNumber(arg) {
653 return typeof arg === 'number';
655 exports.isNumber = isNumber;
657 function isString(arg) {
658 return typeof arg === 'string';
660 exports.isString = isString;
662 function isSymbol(arg) {
663 return typeof arg === 'symbol';
665 exports.isSymbol = isSymbol;
667 function isUndefined(arg) {
668 return arg === undefined;
670 exports.isUndefined = isUndefined;
672 function isRegExp(re) {
673 return objectToString(re) === '[object RegExp]';
675 exports.isRegExp = isRegExp;
677 function isObject(arg) {
678 return arg !== null && typeof arg === 'object';
680 exports.isObject = isObject;
683 return objectToString(d) === '[object Date]';
685 exports.isDate = isDate;
687 function isError(e) {
688 return objectToString(e) === '[object Error]' || e instanceof Error;
690 exports.isError = isError;
692 function isFunction(arg) {
693 return typeof arg === 'function';
695 exports.isFunction = isFunction;
697 function isPrimitive(arg) {
698 return arg === null ||
699 typeof arg !== 'object' && typeof arg !== 'function';
701 exports.isPrimitive = isPrimitive;
703 exports.isBuffer = Buffer.isBuffer;
705 function objectToString(o) {
706 return Object.prototype.toString.call(o);
711 return n < 10 ? '0' + n.toString(10) : n.toString(10);
715 const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
716 'Oct', 'Nov', 'Dec'];
719 function timestamp() {
721 var time = [pad(d.getHours()),
723 pad(d.getSeconds())].join(':');
724 return [d.getDate(), months[d.getMonth()], time].join(' ');
728 // log is just a thin wrapper to console.log that prepends a timestamp
729 exports.log = function() {
730 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
735 * Inherit the prototype methods from one constructor into another.
737 * The Function.prototype.inherits from lang.js rewritten as a standalone
738 * function (not on Function.prototype). NOTE: If this file is to be loaded
739 * during bootstrapping this function needs to be rewritten using some native
740 * functions as prototype setup using normal JavaScript does not work as
741 * expected during bootstrapping (see mirror.js in r114903).
743 * @param {function} ctor Constructor function which needs to inherit the
745 * @param {function} superCtor Constructor function to inherit prototype from.
746 * @throws {TypeError} Will error if either constructor is null, or if
747 * the super constructor lacks a prototype.
749 exports.inherits = function(ctor, superCtor) {
751 if (ctor === undefined || ctor === null)
752 throw new TypeError('The constructor to `inherits` must not be ' +
753 'null or undefined.');
755 if (superCtor === undefined || superCtor === null)
756 throw new TypeError('The super constructor to `inherits` must not ' +
757 'be null or undefined.');
759 if (superCtor.prototype === undefined)
760 throw new TypeError('The super constructor to `inherits` must ' +
761 'have a prototype.');
763 ctor.super_ = superCtor;
764 ctor.prototype = Object.create(superCtor.prototype, {
774 exports._extend = function(origin, add) {
775 // Don't do anything if add isn't an object
776 if (add === null || typeof add !== 'object') return origin;
778 var keys = Object.keys(add);
781 origin[keys[i]] = add[keys[i]];
786 function hasOwnProperty(obj, prop) {
787 return Object.prototype.hasOwnProperty.call(obj, prop);
791 // Deprecated old stuff.
793 exports.p = internalUtil.deprecate(function() {
794 for (var i = 0, len = arguments.length; i < len; ++i) {
795 console.error(exports.inspect(arguments[i]));
797 }, 'util.p is deprecated. Use console.error instead.');
800 exports.exec = internalUtil.deprecate(function() {
801 return require('child_process').exec.apply(this, arguments);
802 }, 'util.exec is deprecated. Use child_process.exec instead.');
805 exports.print = internalUtil.deprecate(function() {
806 for (var i = 0, len = arguments.length; i < len; ++i) {
807 process.stdout.write(String(arguments[i]));
809 }, 'util.print is deprecated. Use console.log instead.');
812 exports.puts = internalUtil.deprecate(function() {
813 for (var i = 0, len = arguments.length; i < len; ++i) {
814 process.stdout.write(arguments[i] + '\n');
816 }, 'util.puts is deprecated. Use console.log instead.');
819 exports.debug = internalUtil.deprecate(function(x) {
820 process.stderr.write('DEBUG: ' + x + '\n');
821 }, 'util.debug is deprecated. Use console.error instead.');
824 exports.error = internalUtil.deprecate(function(x) {
825 for (var i = 0, len = arguments.length; i < len; ++i) {
826 process.stderr.write(arguments[i] + '\n');
828 }, 'util.error is deprecated. Use console.error instead.');
831 exports.pump = internalUtil.deprecate(function(readStream, writeStream, cb) {
832 var callbackCalled = false;
834 function call(a, b, c) {
835 if (cb && !callbackCalled) {
837 callbackCalled = true;
841 readStream.addListener('data', function(chunk) {
842 if (writeStream.write(chunk) === false) readStream.pause();
845 writeStream.addListener('drain', function() {
849 readStream.addListener('end', function() {
853 readStream.addListener('close', function() {
857 readStream.addListener('error', function(err) {
862 writeStream.addListener('error', function(err) {
863 readStream.destroy();
866 }, 'util.pump is deprecated. Use readableStream.pipe instead.');
869 exports._errnoException = function(err, syscall, original) {
870 var errname = uv.errname(err);
871 var message = syscall + ' ' + errname;
873 message += ' ' + original;
874 var e = new Error(message);
882 exports._exceptionWithHostPort = function(err,
888 if (port && port > 0) {
889 details = address + ':' + port;
895 details += ' - Local (' + additional + ')';
897 var ex = exports._errnoException(err, syscall, details);
898 ex.address = address;