- Understanding Node.js
- Installing Node.js
- Working with Node Packages
- Creating a Node.js Application
- Writing Data to the Console
- Summary
- Next
Writing Data to the Console
One of the most useful modules in Node.js during the development process is the console module. This module provides a lot of functionality when writing debug and information statements to the console. The console module allows you to control output to the console, implement time delta output, and write tracebacks and assertions to the console. This section covers using the console module because you need to know it for subsequent chapters in the book.
Because the console module is so widely used, you do not need to load it into your modules using a require() statement. You simply call the console function using console.<function> (<parameters>). Table 3.3 lists the functions available in the console module.
Table 3.3 Member functions of the console module
Function | Description |
log([data],[...]) | Writes data output to the console. The data variable can be a string or an object that can be resolved to a string. Additional parameters can also be sent. For example:console.log("There are %d items", 5); >>There are 5 items |
info([data],[...]) | Same as console.log. |
error([data],[...]) | Same as console.log; however, the output is also sent to stderr. |
warn([data],[...]) | Same as console.error. |
dir(obj) | Writes out a string representation of a JavaScript object to the console. For example:console.dir({name:"Brad", role:"Author"}); >> { name: 'Brad', role: 'Author' } |
time(label) | Assigns a current timestamp with ms precision to the string label. |
timeEnd(label) | Creates a delta between the current time and the timestamp assigned to label and outputs the results. For example:console.time("FileWrite"); f.write(data); //takes about 500ms console.timeEnd("FileWrite"); >> FileWrite: 500ms |
trace(label) | Writes out a stack trace of the current position in code to stderr. For example:module.trace("traceMark"); >>Trace: traceMark at Object.<anonymous> (C:\test.js:24:9) at Module._compile (module.js:456:26) at Object.Module._ext.js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain(module.js:497:10) at startup (node.js:119:16) at node.js:901:3 |
assert(expression, [message]) |
Writes the message and stack trace to the console if expression evaluates to false. |