頗有用的調試方法。能夠經過 util.debuglog(name) 來建立一個調試fn,這個fn的特色是,只有在運行程序時候,聲明環境變量NODE_DEBUG=name,纔會打印出調試信息。html
能夠看下面的例子,直接運行 node debuglog.js
,沒有任何輸出。須要NODE_DEBUG=foo
,纔會有打印信息.node
var util = require('util'); var logger = util.debuglog('foo'); logger('hello');
以下所示,注意,6347 是當前進程id。git
➜ 2016.12.02-util git:(master) ✗ NODE_DEBUG=foo node debuglog.js
FOO 6347: hello world
此外,還能夠一次指定多個name
,經過逗號分隔。shell
var util = require('util'); var firstLogger = util.debuglog('first'); var secondLogger = util.debuglog('second'); var thirdLogger = util.debuglog('third'); firstLogger('hello'); secondLogger('hello'); thirdLogger('hello');
運行以下:api
FOO 6347: hello world
➜ 2016.12.02-util git:(master) ✗ NODE_DEBUG=first,second node debuglog.js
FIRST 6456: hello
SECOND 6456: hello
將fn
包裹一層,並返回一個新的函數fn2
。調用fn2
時,一樣完成fn
原有的功能,但同時會打印出錯誤日誌,提示方法已做廢,具體的提示信息就是第二個參數str
。數組
var util = require('util'); var foo = function(){ console.log('foo'); }; var foo2 = util.deprecate(foo, 'foo is deprecate'); foo2(); // 輸出以下: // foo // (node:6608) DeprecationWarning: foo is deprecate
若是嫌錯誤提示信息煩人,能夠經過--no-deprecation
參數禁掉,能夠參考這裏。函數
➜ 2016.12.02-util git:(master) ✗ node --no-deprecation deprecate.js
foo
格式化打印你們應該比較熟悉了,基本每種語言裏都有本身的實現,直接上例子。ui
var util = require('util'); console.log( util.format('hello %s', 'world') ); // 輸出:hello world console.log( util.format('1 + 1 = %d', 2) ); // 輸出:1 + 1 = 2 console.log( util.format('info: %j', {nick: 'chyingp'}) ); // 輸出:info: {"nick":"chyingp"} console.log( util.format('%s is %d age old', 'chyingp') ); // 輸出:chyingp is %d age old console.log( util.format('%s is a man', 'chyingp', 'indeed') ); // 輸出:chyingp is a man indeed
很是實用的一個方法,參數說明以下:spa
var util = require('util'); var obj = {}; Object.defineProperty(obj, 'nick', { enumerable: false, value: 'chyingp' }); console.log( util.inspect(obj) ); // 輸出:{} console.log( util.inspect(obj, {showHidden: true}) ); // 輸出:{ [nick]: 'chyingp' }