NodeJS學習筆記 (18)基礎調試-console(ok)
阿新 • • 發佈:2018-06-18
實用 log ger 擴展 rtu ML class cti right
模塊概覽
console模塊提供了基礎的調試功能。使用很簡單,常用的API主要有 console.log()、console.error()。
此外,可以基於Console類,方便的擴展出自己的console實例,比如把調試信息打印到文件裏,而部署輸出在控制臺上。
直接看例子。
基礎例子
無特殊說明,日誌都是默認打印到控制臺。最常用的是console.log()、console.error()兩個方法。
- console.log(msg):普通日誌打印。
- console.error(msg):錯誤日誌打印。
- console.info(msg):等同於console.log(msg)
- console.warn(msg):等同於console.error(msg)
例子如下:
console.log(‘log: hello‘); console.log(‘log: hello‘, ‘chyingp‘); console.log(‘log: hello %s‘, ‘chyingp‘); console.error(‘error: hello‘); console.error(‘error: hello‘, ‘chyingp‘); console.error(‘error: hello %s‘, ‘chyingp‘); // 輸出如下: // log: hello // log: hello chyingp // log: hello chyingp // error: hello // error: hello chyingp // error: hello chyingp
自定義stdout
可以通過 new console.Console(stdout, stderr) 來創建自定義的console實例,這個功能很實用。
比如你想將調試信息打印到本地文件,那麽,就可以通過如下代碼實現。
var fs = require(‘fs‘); var file = fs.createWriteStream(‘./stdout.txt‘); var logger = new console.Console(file, file); logger.log(‘hello‘); logger.log(‘word‘); // 備註:內容輸出到 stdout.txt裏,而不是打印到控制臺
計時
通過console.time(label)
和console.timeEnd(label)
,來打印出兩個時間點之間的時間差,單位是毫秒,例子如下。
var timeLabel = ‘hello‘ console.time(timeLabel); setTimeout(console.timeEnd, 1000, timeLabel); // 輸入出入: // hello: 1005.505ms
斷言
通過 console.assert(value, message) 進行斷言。如果value不為true,那麽拋出AssertionError
異常,並中斷程序執行。
如下代碼所示,第二個斷言報錯,程序停止執行。
console.assert(true, ‘1、right‘);
console.assert(false, ‘2、right‘, ‘2、wrong‘);
// 輸出如下:
// assert.js:90
// throw new assert.AssertionError({
// ^
// AssertionError: 2、right 2、wrong
// at Console.assert (console.js:95:23)
為避免程序異常退出,需要對上面的異常進行處理,比如:
try{ console.assert(false, ‘error occurred‘); }catch(e){ console.log(e.message); } // 輸出如下: // error occurred
打印錯誤堆棧:console.trace(msg)
將msg打印到標準錯誤輸出流裏,包含當前代碼的位置和堆棧信息。
console.trace(‘trace is called‘); // 輸出如下: // Trace: trace is called // at Object.<anonymous> (/Users/a/Documents/git-code/nodejs-learning-guide/examples/2016.12.01-console/trace.js:1:71) // at Module._compile (module.js:541:32) // at Object.Module._extensions..js (module.js:550:10) // at Module.load (module.js:456:32) // at tryModuleLoad (module.js:415:12) // at Function.Module._load (module.js:407:3) // at Function.Module.runMain (module.js:575:10) // at startup (node.js:160:18) // at node.js:445:3
深層打印
很少關註 console.dir(obj),因為大部分時候表現跟 console.log(obj) 差不多,看例子
var obj = {
nick: ‘chyingp‘
};
console.log(obj); // 輸出:{ nick: ‘chyingp‘ }
console.dir(obj); // 輸出:{ nick: ‘chyingp‘ }
但當obj的層級比較深時,用處就出來了。可以通過depth
自定義打印的層級數,默認是2,這對於調試很有幫助。
var obj2 = {
human: {
man: {
info: {
nick: ‘chyingp‘
}
}
}
};
console.log(obj2); // 輸出:{ human: { man: { info: [Object] } } }
console.dir(obj2); // 輸出:{ human: { man: { info: [Object] } } }
console.dir(obj2, {depth: 3}); // 輸出:{ human: { man: { info: { nick: ‘chyingp‘ } } } }
相關鏈接
官方文檔:https://nodejs.org/api/console.html
NodeJS學習筆記 (18)基礎調試-console(ok)