console.log 大概是每個 Node.js 開發者最早認識、也最常使用的方法。它的職責很單純:把內容印到標準輸出流,並以換行符結尾。
console.log([data], [...])
printf() 的格式輸出。var count = 1234;
console.log('count: %d', count);
// 輸出結果 count : 1234;
console.log('Hello world');
// 輸出結果 Hello world;
console.log('count: %d');
// 輸出結果 count: %d;
從第三個例子可以看到:當沒有提供對應參數時,%d 佔位符會原樣保留,不會被替換。
它的實作非常直觀——把格式化後的字串寫入標準輸出流(stdout),並附上換行:
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
正是這個簡潔的設計,讓它成為 Node.js 除錯與日誌輸出最可靠的夥伴。