doc: improvements to console.markdown copy
[platform/upstream/nodejs.git] / lib / console.js
1 'use strict';
2
3 const util = require('util');
4
5 function Console(stdout, stderr) {
6   if (!(this instanceof Console)) {
7     return new Console(stdout, stderr);
8   }
9   if (!stdout || typeof stdout.write !== 'function') {
10     throw new TypeError('Console expects a writable stream instance');
11   }
12   if (!stderr) {
13     stderr = stdout;
14   }
15   var prop = {
16     writable: true,
17     enumerable: false,
18     configurable: true
19   };
20   prop.value = stdout;
21   Object.defineProperty(this, '_stdout', prop);
22   prop.value = stderr;
23   Object.defineProperty(this, '_stderr', prop);
24   prop.value = new Map();
25   Object.defineProperty(this, '_times', prop);
26
27   // bind the prototype functions to this Console instance
28   var keys = Object.keys(Console.prototype);
29   for (var v = 0; v < keys.length; v++) {
30     var k = keys[v];
31     this[k] = this[k].bind(this);
32   }
33 }
34
35 Console.prototype.log = function() {
36   this._stdout.write(util.format.apply(this, arguments) + '\n');
37 };
38
39
40 Console.prototype.info = Console.prototype.log;
41
42
43 Console.prototype.warn = function() {
44   this._stderr.write(util.format.apply(this, arguments) + '\n');
45 };
46
47
48 Console.prototype.error = Console.prototype.warn;
49
50
51 Console.prototype.dir = function(object, options) {
52   this._stdout.write(util.inspect(object, util._extend({
53     customInspect: false
54   }, options)) + '\n');
55 };
56
57
58 Console.prototype.time = function(label) {
59   this._times.set(label, Date.now());
60 };
61
62
63 Console.prototype.timeEnd = function(label) {
64   var time = this._times.get(label);
65   if (!time) {
66     throw new Error('No such label: ' + label);
67   }
68   var duration = Date.now() - time;
69   this.log('%s: %dms', label, duration);
70 };
71
72
73 Console.prototype.trace = function trace() {
74   // TODO probably can to do this better with V8's debug object once that is
75   // exposed.
76   var err = new Error();
77   err.name = 'Trace';
78   err.message = util.format.apply(this, arguments);
79   Error.captureStackTrace(err, trace);
80   this.error(err.stack);
81 };
82
83
84 Console.prototype.assert = function(expression) {
85   if (!expression) {
86     var arr = Array.prototype.slice.call(arguments, 1);
87     require('assert').ok(false, util.format.apply(this, arr));
88   }
89 };
90
91
92 module.exports = new Console(process.stdout, process.stderr);
93 module.exports.Console = Console;