1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
22 var formatRegExp = /%[sdj%]/g;
23 exports.format = function(f) {
26 for (var i = 0; i < arguments.length; i++) {
27 objects.push(inspect(arguments[i]));
29 return objects.join(' ');
34 var len = args.length;
35 var str = String(f).replace(formatRegExp, function(x) {
36 if (x === '%%') return '%';
37 if (i >= len) return x;
39 case '%s': return String(args[i++]);
40 case '%d': return Number(args[i++]);
43 return JSON.stringify(args[i++]);
51 for (var x = args[i]; i < len; x = args[++i]) {
52 if (isNull(x) || !isObject(x)) {
55 str += ' ' + inspect(x);
62 // Mark that a method should not be used.
63 // Returns a modified function which warns once by default.
64 // If --no-deprecation is set, then it is a no-op.
65 exports.deprecate = function(fn, msg) {
66 // Allow for deprecating things in the process of starting up.
67 if (isUndefined(global.process)) {
69 return exports.deprecate(fn, msg).apply(this, arguments);
73 if (process.noDeprecation === true) {
78 function deprecated() {
80 if (process.throwDeprecation) {
82 } else if (process.traceDeprecation) {
89 return fn.apply(this, arguments);
98 exports.debuglog = function(set) {
99 if (isUndefined(debugEnviron))
100 debugEnviron = process.env.NODE_DEBUG || '';
101 set = set.toUpperCase();
103 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
104 var pid = process.pid;
105 debugs[set] = function() {
106 var msg = exports.format.apply(exports, arguments);
107 console.error('%s %d: %s', set, pid, msg);
110 debugs[set] = function() {};
118 * Echos the value of a value. Trys to print the value out
119 * in the best way possible given the different types.
121 * @param {Object} obj The object to print out.
122 * @param {Object} opts Optional options object that alters the output.
124 /* legacy: obj, showHidden, depth, colors*/
125 function inspect(obj, opts) {
129 stylize: stylizeNoColor
132 if (arguments.length >= 3) ctx.depth = arguments[2];
133 if (arguments.length >= 4) ctx.colors = arguments[3];
134 if (isBoolean(opts)) {
136 ctx.showHidden = opts;
138 // got an "options" object
139 exports._extend(ctx, opts);
141 // set default options
142 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
143 if (isUndefined(ctx.depth)) ctx.depth = 2;
144 if (isUndefined(ctx.colors)) ctx.colors = false;
145 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
146 if (ctx.colors) ctx.stylize = stylizeWithColor;
147 return formatValue(ctx, obj, ctx.depth);
149 exports.inspect = inspect;
152 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
156 'underline' : [4, 24],
164 'magenta' : [35, 39],
169 // Don't use 'blue' not visible on cmd.exe
179 // "name": intentionally not styling
184 function stylizeWithColor(str, styleType) {
185 var style = inspect.styles[styleType];
188 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
189 '\u001b[' + inspect.colors[style][1] + 'm';
196 function stylizeNoColor(str, styleType) {
201 function arrayToHash(array) {
204 array.forEach(function(val, idx) {
212 function formatValue(ctx, value, recurseTimes) {
213 // Provide a hook for user-specified inspect functions.
214 // Check that value is an object with an inspect function on it
215 if (ctx.customInspect &&
217 isFunction(value.inspect) &&
218 // Filter out the util module, it's inspect function is special
219 value.inspect !== exports.inspect &&
220 // Also filter out any prototype objects using the circular check.
221 !(value.constructor && value.constructor.prototype === value)) {
222 var ret = value.inspect(recurseTimes, ctx);
223 if (!isString(ret)) {
224 ret = formatValue(ctx, ret, recurseTimes);
229 // Primitive types cannot have properties
230 var primitive = formatPrimitive(ctx, value);
235 // Look up the keys of the object.
236 var keys = Object.keys(value);
237 var visibleKeys = arrayToHash(keys);
239 if (ctx.showHidden) {
240 keys = Object.getOwnPropertyNames(value);
243 // This could be a boxed primitive (new String(), etc.), check valueOf()
244 // NOTE: Avoid calling `valueOf` on `Date` instance because it will return
245 // a number which, when object has some additional user-stored `keys`,
246 // will be printed out.
250 // the .valueOf() call can fail for a multitude of reasons
252 raw = value.valueOf();
258 // for boxed Strings, we have to remove the 0-n indexed entries,
259 // since they just noisey up the output and are redundant
260 keys = keys.filter(function(key) {
261 return !(key >= 0 && key < raw.length);
265 // Some type of object without properties can be shortcutted.
266 if (keys.length === 0) {
267 if (isFunction(value)) {
268 var name = value.name ? ': ' + value.name : '';
269 return ctx.stylize('[Function' + name + ']', 'special');
271 if (isRegExp(value)) {
272 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
275 return ctx.stylize(Date.prototype.toString.call(value), 'date');
277 if (isError(value)) {
278 return formatError(value);
280 // now check the `raw` value to handle boxed primitives
282 formatted = formatPrimitiveNoColor(ctx, raw);
283 return ctx.stylize('[String: ' + formatted + ']', 'string');
286 formatted = formatPrimitiveNoColor(ctx, raw);
287 return ctx.stylize('[Number: ' + formatted + ']', 'number');
289 if (isBoolean(raw)) {
290 formatted = formatPrimitiveNoColor(ctx, raw);
291 return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean');
295 var base = '', array = false, braces = ['{', '}'];
297 // Make Array say that they are Array
298 if (isArray(value)) {
303 // Make functions say that they are functions
304 if (isFunction(value)) {
305 var n = value.name ? ': ' + value.name : '';
306 base = ' [Function' + n + ']';
309 // Make RegExps say that they are RegExps
310 if (isRegExp(value)) {
311 base = ' ' + RegExp.prototype.toString.call(value);
314 // Make dates with properties first say the date
316 base = ' ' + Date.prototype.toUTCString.call(value);
319 // Make error with message first say the error
320 if (isError(value)) {
321 base = ' ' + formatError(value);
324 // Make boxed primitive Strings look like such
326 formatted = formatPrimitiveNoColor(ctx, raw);
327 base = ' ' + '[String: ' + formatted + ']';
330 // Make boxed primitive Numbers look like such
332 formatted = formatPrimitiveNoColor(ctx, raw);
333 base = ' ' + '[Number: ' + formatted + ']';
336 // Make boxed primitive Booleans look like such
337 if (isBoolean(raw)) {
338 formatted = formatPrimitiveNoColor(ctx, raw);
339 base = ' ' + '[Boolean: ' + formatted + ']';
342 if (keys.length === 0 && (!array || value.length === 0)) {
343 return braces[0] + base + braces[1];
346 if (recurseTimes < 0) {
347 if (isRegExp(value)) {
348 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
350 return ctx.stylize('[Object]', 'special');
354 ctx.seen.push(value);
358 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
360 output = keys.map(function(key) {
361 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
367 return reduceToSingleString(output, base, braces);
371 function formatPrimitive(ctx, value) {
372 if (isUndefined(value))
373 return ctx.stylize('undefined', 'undefined');
374 if (isString(value)) {
375 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
376 .replace(/'/g, "\\'")
377 .replace(/\\"/g, '"') + '\'';
378 return ctx.stylize(simple, 'string');
380 if (isNumber(value)) {
381 // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
382 // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
383 if (value === 0 && 1 / value < 0)
384 return ctx.stylize('-0', 'number');
385 return ctx.stylize('' + value, 'number');
387 if (isBoolean(value))
388 return ctx.stylize('' + value, 'boolean');
389 // For some reason typeof null is "object", so special case here.
391 return ctx.stylize('null', 'null');
392 // es6 symbol primitive
394 return ctx.stylize(value.toString(), 'symbol');
398 function formatPrimitiveNoColor(ctx, value) {
399 var stylize = ctx.stylize;
400 ctx.stylize = stylizeNoColor;
401 var str = formatPrimitive(ctx, value);
402 ctx.stylize = stylize;
407 function formatError(value) {
408 return '[' + Error.prototype.toString.call(value) + ']';
412 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
414 for (var i = 0, l = value.length; i < l; ++i) {
415 if (hasOwnProperty(value, String(i))) {
416 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
422 keys.forEach(function(key) {
423 if (!key.match(/^\d+$/)) {
424 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
432 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
434 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
437 str = ctx.stylize('[Getter/Setter]', 'special');
439 str = ctx.stylize('[Getter]', 'special');
443 str = ctx.stylize('[Setter]', 'special');
446 if (!hasOwnProperty(visibleKeys, key)) {
447 name = '[' + key + ']';
450 if (ctx.seen.indexOf(desc.value) < 0) {
451 if (isNull(recurseTimes)) {
452 str = formatValue(ctx, desc.value, null);
454 str = formatValue(ctx, desc.value, recurseTimes - 1);
456 if (str.indexOf('\n') > -1) {
458 str = str.split('\n').map(function(line) {
460 }).join('\n').substr(2);
462 str = '\n' + str.split('\n').map(function(line) {
468 str = ctx.stylize('[Circular]', 'special');
471 if (isUndefined(name)) {
472 if (array && key.match(/^\d+$/)) {
475 name = JSON.stringify('' + key);
476 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
477 name = name.substr(1, name.length - 2);
478 name = ctx.stylize(name, 'name');
480 name = name.replace(/'/g, "\\'")
481 .replace(/\\"/g, '"')
482 .replace(/(^"|"$)/g, "'")
483 .replace(/\\\\/g, '\\');
484 name = ctx.stylize(name, 'string');
488 return name + ': ' + str;
492 function reduceToSingleString(output, base, braces) {
493 var length = output.reduce(function(prev, cur) {
494 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
499 (base === '' ? '' : base + '\n ') +
501 output.join(',\n ') +
506 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
510 // NOTE: These type checking functions intentionally don't use `instanceof`
511 // because it is fragile and can be easily faked with `Object.create()`.
512 var isArray = exports.isArray = Array.isArray;
514 function isBoolean(arg) {
515 return typeof arg === 'boolean';
517 exports.isBoolean = isBoolean;
519 function isNull(arg) {
522 exports.isNull = isNull;
524 function isNullOrUndefined(arg) {
527 exports.isNullOrUndefined = isNullOrUndefined;
529 function isNumber(arg) {
530 return typeof arg === 'number';
532 exports.isNumber = isNumber;
534 function isString(arg) {
535 return typeof arg === 'string';
537 exports.isString = isString;
539 function isSymbol(arg) {
540 return typeof arg === 'symbol';
542 exports.isSymbol = isSymbol;
544 function isUndefined(arg) {
545 return arg === void 0;
547 exports.isUndefined = isUndefined;
549 function isRegExp(re) {
550 return isObject(re) && objectToString(re) === '[object RegExp]';
552 exports.isRegExp = isRegExp;
554 function isObject(arg) {
555 return typeof arg === 'object' && arg !== null;
557 exports.isObject = isObject;
560 return isObject(d) && objectToString(d) === '[object Date]';
562 exports.isDate = isDate;
564 function isError(e) {
565 return isObject(e) &&
566 (objectToString(e) === '[object Error]' || e instanceof Error);
568 exports.isError = isError;
570 function isFunction(arg) {
571 return typeof arg === 'function';
573 exports.isFunction = isFunction;
575 function isPrimitive(arg) {
576 return arg === null ||
577 typeof arg === 'boolean' ||
578 typeof arg === 'number' ||
579 typeof arg === 'string' ||
580 typeof arg === 'symbol' || // ES6 symbol
581 typeof arg === 'undefined';
583 exports.isPrimitive = isPrimitive;
585 function isBuffer(arg) {
586 return arg instanceof Buffer;
588 exports.isBuffer = isBuffer;
590 function objectToString(o) {
591 return Object.prototype.toString.call(o);
596 return n < 10 ? '0' + n.toString(10) : n.toString(10);
600 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
601 'Oct', 'Nov', 'Dec'];
604 function timestamp() {
606 var time = [pad(d.getHours()),
608 pad(d.getSeconds())].join(':');
609 return [d.getDate(), months[d.getMonth()], time].join(' ');
613 // log is just a thin wrapper to console.log that prepends a timestamp
614 exports.log = function() {
615 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
620 * Inherit the prototype methods from one constructor into another.
622 * The Function.prototype.inherits from lang.js rewritten as a standalone
623 * function (not on Function.prototype). NOTE: If this file is to be loaded
624 * during bootstrapping this function needs to be rewritten using some native
625 * functions as prototype setup using normal JavaScript does not work as
626 * expected during bootstrapping (see mirror.js in r114903).
628 * @param {function} ctor Constructor function which needs to inherit the
630 * @param {function} superCtor Constructor function to inherit prototype from.
632 exports.inherits = function(ctor, superCtor) {
633 ctor.super_ = superCtor;
634 ctor.prototype = Object.create(superCtor.prototype, {
644 exports._extend = function(origin, add) {
645 // Don't do anything if add isn't an object
646 if (!add || !isObject(add)) return origin;
648 var keys = Object.keys(add);
651 origin[keys[i]] = add[keys[i]];
656 function hasOwnProperty(obj, prop) {
657 return Object.prototype.hasOwnProperty.call(obj, prop);
661 // Deprecated old stuff.
663 exports.p = exports.deprecate(function() {
664 for (var i = 0, len = arguments.length; i < len; ++i) {
665 console.error(exports.inspect(arguments[i]));
667 }, 'util.p: Use console.error() instead');
670 exports.exec = exports.deprecate(function() {
671 return require('child_process').exec.apply(this, arguments);
672 }, 'util.exec is now called `child_process.exec`.');
675 exports.print = exports.deprecate(function() {
676 for (var i = 0, len = arguments.length; i < len; ++i) {
677 process.stdout.write(String(arguments[i]));
679 }, 'util.print: Use console.log instead');
682 exports.puts = exports.deprecate(function() {
683 for (var i = 0, len = arguments.length; i < len; ++i) {
684 process.stdout.write(arguments[i] + '\n');
686 }, 'util.puts: Use console.log instead');
689 exports.debug = exports.deprecate(function(x) {
690 process.stderr.write('DEBUG: ' + x + '\n');
691 }, 'util.debug: Use console.error instead');
694 exports.error = exports.deprecate(function(x) {
695 for (var i = 0, len = arguments.length; i < len; ++i) {
696 process.stderr.write(arguments[i] + '\n');
698 }, 'util.error: Use console.error instead');
701 exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
702 var callbackCalled = false;
704 function call(a, b, c) {
705 if (callback && !callbackCalled) {
707 callbackCalled = true;
711 readStream.addListener('data', function(chunk) {
712 if (writeStream.write(chunk) === false) readStream.pause();
715 writeStream.addListener('drain', function() {
719 readStream.addListener('end', function() {
723 readStream.addListener('close', function() {
727 readStream.addListener('error', function(err) {
732 writeStream.addListener('error', function(err) {
733 readStream.destroy();
736 }, 'util.pump(): Use readableStream.pipe() instead');
740 exports._errnoException = function(err, syscall, original) {
741 if (isUndefined(uv)) uv = process.binding('uv');
742 var errname = uv.errname(err);
743 var message = syscall + ' ' + errname;
745 message += ' ' + original;
746 var e = new Error(message);