node/lib/console.js

90 lines
1.8 KiB
JavaScript
Raw Normal View History

2010-12-01 03:18:02 +08:00
var writeError = process.binding('stdio').writeError;
// console object
var formatRegExp = /%[sdj]/g;
2010-12-02 09:29:11 +08:00
function format(f) {
var util = require('util');
2010-12-01 03:18:02 +08:00
if (typeof f !== 'string') {
var objects = [];
2010-12-01 03:18:02 +08:00
for (var i = 0; i < arguments.length; i++) {
objects.push(util.inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
2010-12-02 09:29:11 +08:00
var str = String(f).replace(formatRegExp, function(x) {
2010-12-01 03:18:02 +08:00
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
2010-12-01 03:18:02 +08:00
case '%j': return JSON.stringify(args[i++]);
default:
return x;
}
});
for (var len = args.length, x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + util.inspect(x);
}
2010-12-01 03:18:02 +08:00
}
return str;
}
2010-12-02 09:29:11 +08:00
exports.log = function() {
2010-12-01 03:18:02 +08:00
process.stdout.write(format.apply(this, arguments) + '\n');
};
exports.info = exports.log;
2010-12-02 09:29:11 +08:00
exports.warn = function() {
2010-12-01 03:18:02 +08:00
writeError(format.apply(this, arguments) + '\n');
};
exports.error = exports.warn;
2010-12-02 09:29:11 +08:00
exports.dir = function(object) {
2010-12-01 03:18:02 +08:00
var util = require('util');
process.stdout.write(util.inspect(object) + '\n');
};
var times = {};
2010-12-02 09:29:11 +08:00
exports.time = function(label) {
2010-12-01 03:18:02 +08:00
times[label] = Date.now();
};
2010-12-02 09:29:11 +08:00
exports.timeEnd = function(label) {
2010-12-01 03:18:02 +08:00
var duration = Date.now() - times[label];
exports.log('%s: %dms', label, duration);
};
2010-12-02 09:29:11 +08:00
exports.trace = function(label) {
2010-12-01 03:18:02 +08:00
// TODO probably can to do this better with V8's debug object once that is
// exposed.
var err = new Error;
err.name = 'Trace';
err.message = label || '';
Error.captureStackTrace(err, arguments.callee);
console.error(err.stack);
};
2010-12-02 09:29:11 +08:00
exports.assert = function(expression) {
if (!expression) {
2010-12-01 03:18:02 +08:00
var arr = Array.prototype.slice.call(arguments, 1);
process.assert(false, format.apply(this, arr));
}
};