node.js 5.87 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
1
2
3
4
/**
 * Module dependencies.
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
5
6
var tty = require('tty');
var util = require('util');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
7
8
9

/**
 * This is the Node.js implementation of `debug()`.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
10
11
 *
 * Expose `debug()` as the module.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
12
13
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
14
exports = module.exports = require('./debug');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;

/**
 * Colors.
 */

exports.colors = [6, 2, 3, 4, 5, 1];

/**
 * Build up the default `inspectOpts` object from the environment variables.
 *
 *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  return /^debug_/i.test(key);
}).reduce(function (obj, key) {
  // camel-case
  var prop = key
    .substring(6)
    .toLowerCase()
    .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });

  // coerce string value into JS value
  var val = process.env[key];
  if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  else if (val === 'null') val = null;
  else val = Number(val);

  obj[prop] = val;
  return obj;
Rosanny Sihombing's avatar
Rosanny Sihombing committed
52
53
}, {});

Rosanny Sihombing's avatar
Rosanny Sihombing committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
 * The file descriptor to write the `debug()` calls to.
 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
 *
 *   $ DEBUG_FD=3 node script.js 3>debug.log
 */

var fd = parseInt(process.env.DEBUG_FD, 10) || 2;

if (1 !== fd && 2 !== fd) {
  util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
}

var stream = 1 === fd ? process.stdout :
             2 === fd ? process.stderr :
             createWritableStdioStream(fd);

Rosanny Sihombing's avatar
Rosanny Sihombing committed
71
72
73
74
75
/**
 * Is stdout a TTY? Colored output is enabled when `true`.
 */

function useColors() {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
76
77
78
  return 'colors' in exports.inspectOpts
    ? Boolean(exports.inspectOpts.colors)
    : tty.isatty(fd);
Rosanny Sihombing's avatar
Rosanny Sihombing committed
79
80
}

Rosanny Sihombing's avatar
Rosanny Sihombing committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
 * Map %o to `util.inspect()`, all on a single line.
 */

exports.formatters.o = function(v) {
  this.inspectOpts.colors = this.useColors;
  return util.inspect(v, this.inspectOpts)
    .split('\n').map(function(str) {
      return str.trim()
    }).join(' ');
};

/**
 * Map %o to `util.inspect()`, allowing multiple lines if needed.
 */

exports.formatters.O = function(v) {
  this.inspectOpts.colors = this.useColors;
  return util.inspect(v, this.inspectOpts);
};

Rosanny Sihombing's avatar
Rosanny Sihombing committed
102
103
104
105
106
107
108
/**
 * Adds ANSI color escape codes if enabled.
 *
 * @api public
 */

function formatArgs(args) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
109
110
111
112
113
114
115
116
117
118
119
120
121
  var name = this.namespace;
  var useColors = this.useColors;

  if (useColors) {
    var c = this.color;
    var prefix = '  \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';

    args[0] = prefix + args[0].split('\n').join('\n' + prefix);
    args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  } else {
    args[0] = new Date().toUTCString()
      + ' ' + name + ' ' + args[0];
  }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
122
123
124
}

/**
Rosanny Sihombing's avatar
Rosanny Sihombing committed
125
 * Invokes `util.format()` with the specified arguments and writes to `stream`.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
126
127
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
128
129
function log() {
  return stream.write(util.format.apply(util, arguments) + '\n');
Rosanny Sihombing's avatar
Rosanny Sihombing committed
130
131
132
133
134
135
136
137
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */
Rosanny Sihombing's avatar
Rosanny Sihombing committed
138

Rosanny Sihombing's avatar
Rosanny Sihombing committed
139
function save(namespaces) {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
140
141
142
143
144
145
146
  if (null == namespaces) {
    // If you set a process.env field to null or undefined, it gets cast to the
    // string 'null' or 'undefined'. Just delete instead.
    delete process.env.DEBUG;
  } else {
    process.env.DEBUG = namespaces;
  }
Rosanny Sihombing's avatar
Rosanny Sihombing committed
147
148
149
150
151
152
153
154
155
156
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
Rosanny Sihombing's avatar
Rosanny Sihombing committed
157
  return process.env.DEBUG;
Rosanny Sihombing's avatar
Rosanny Sihombing committed
158
159
160
}

/**
Rosanny Sihombing's avatar
Rosanny Sihombing committed
161
 * Copied from `node/src/node.js`.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
162
 *
Rosanny Sihombing's avatar
Rosanny Sihombing committed
163
164
 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
165
166
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
function createWritableStdioStream (fd) {
  var stream;
  var tty_wrap = process.binding('tty_wrap');

  // Note stream._type is used for test-module-load-list.js

  switch (tty_wrap.guessHandleType(fd)) {
    case 'TTY':
      stream = new tty.WriteStream(fd);
      stream._type = 'tty';

      // Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;

    case 'FILE':
      var fs = require('fs');
      stream = new fs.SyncWriteStream(fd, { autoClose: false });
      stream._type = 'fs';
      break;

    case 'PIPE':
    case 'TCP':
      var net = require('net');
      stream = new net.Socket({
        fd: fd,
        readable: false,
        writable: true
      });

      // FIXME Should probably have an option in net.Socket to create a
      // stream from an existing fd which is writable only. But for now
      // we'll just add this hack and set the `readable` member to false.
      // Test: ./node test/fixtures/echo.js < /etc/passwd
      stream.readable = false;
      stream.read = null;
      stream._type = 'pipe';

      // FIXME Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;

    default:
      // Probably an error on in uv_guess_handle()
      throw new Error('Implement me. Unknown stream file type!');
  }

  // For supporting legacy API we put the FD here.
  stream.fd = fd;

  stream._isStdio = true;

  return stream;
Rosanny Sihombing's avatar
Rosanny Sihombing committed
226
227
}

Rosanny Sihombing's avatar
Rosanny Sihombing committed
228
/**
Rosanny Sihombing's avatar
Rosanny Sihombing committed
229
230
231
232
 * Init logic for `debug` instances.
 *
 * Create a new `inspectOpts` object in case `useColors` is set
 * differently for a particular `debug` instance.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
233
234
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
235
236
237
238
239
240
241
242
function init (debug) {
  debug.inspectOpts = {};

  var keys = Object.keys(exports.inspectOpts);
  for (var i = 0; i < keys.length; i++) {
    debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  }
}
Rosanny Sihombing's avatar
Rosanny Sihombing committed
243

Rosanny Sihombing's avatar
Rosanny Sihombing committed
244
/**
Rosanny Sihombing's avatar
Rosanny Sihombing committed
245
 * Enable namespaces listed in `process.env.DEBUG` initially.
Rosanny Sihombing's avatar
Rosanny Sihombing committed
246
247
 */

Rosanny Sihombing's avatar
Rosanny Sihombing committed
248
exports.enable(load());