NodeJS學習筆記 (27)實用工具模塊-util(ok)

debuglog(section)

頗有用的調試方法。能夠經過 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

將方法標識爲做廢:util.deprecate(fn, str)

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

格式化打印:util.format(format[, ...args])

格式化打印你們應該比較熟悉了,基本每種語言裏都有本身的實現,直接上例子。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


調試方法:util.inspect(obj[, options])

很是實用的一個方法,參數說明以下:spa

  • obj:js原始值,或者對象。
  • options:配置參數,包含下面選項
    • showHidden:若是是true的話,obj的非枚舉屬性也會被展現出來。默認是false。
    • depth:若是obj是對象,那麼,depth限制對象遞歸展現的層級,這對可讀性有必定的好處,默認是2。若是設置爲null,則不作限制。
    • colors:自定義配色方案。
    • showProxy:
    • maxArrayLength:若是obj是數組,那麼限制最大可展現的數組個數。默認是100,若是設置爲null,則不作限制。若是設置爲0或負數,則一個都不展現。
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' }
相關文章
相關標籤/搜索