Node.js console module
consoleThe module is one of the most commonly used built-in modules in Node.js, providing a simple debugging console similar to the JavaScriptconsoleobject in the browser.
Basic usage of the console module
1. Print general information
console.log()It is the most commonly used method, used for printing general information:
Example
// Output: Hello, Node.js!
2. Print error messages
console.error()It is used to print error messages, output to stderr by default:
Example
// Output (red): This is an error message
3. Print warning messages
console.warn()It is used to print warning messages:
Example
// Output (yellow): This is a warning message
4. Print informational messages
console.info()andconsole.log()Similar to console.log, it is used for printing informational messages:
Example
// Output: This is an informational message
Advanced features of the console module
1. Formatted output
The console module supports formatted output similar to the printf() style in C language:
Example
const age = 25;
console.log('Name: %s, Age: %d', name, age);
// Output: Name: Alice, Age: 25
Supported format placeholders:
%s- String%d- Number (integer or float)%i- Integer%f- Float%o- Object%j- JSON
2. Timing functionality
console.time()andconsole.timeEnd()It can be used to measure code execution time:
Example
const arr = [];
for (let i = 0; i < 1000000; i++) {
arr.push(i);
}
console.timeEnd('array test');
// Output: array test: 12.345ms
3. Grouped output
console.group()andconsole.groupEnd()It can create collapsible message groups:
Example
console.log('Name: Alice');
console.log('Age: 25');
console.groupEnd();
4. Table output
console.table()It can output arrays or objects in table form:
Example
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
console.table(users);
5. Assertion testing
console.assert()It is used for simple assertion testing:
Example
console.assert(x === 10, 'x should be 10');
// Output when assertion is false: Assertion failed: x should be 10
Configuration options for the console module
1. Custom output streams
You can create a custom Console instance and specify different output streams:
Example
const fs = require('fs');
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
const logger = new Console(output, errorOutput);
logger.log('This will be written to stdout.log');
logger.error('This will be written to stderr.log');
2. Colors and styles
In terminals that support ANSI colors, console output can be colored:
Example
Or use third-party libraries such aschalkto simplify color control:
Example
console.log(chalk.blue('Blue text'));
Best practices
- Production environment logs: In production environments, it is recommended to use a dedicated logging library such as
winstonorbunyaninstead of console. - Avoid overuse: Only use console during development and debugging; unnecessary console statements should be removed from production code.
- Performance considerations: console.log is synchronous, so use it with caution in performance-sensitive scenarios.
- Error handling: Use console.error to record error messages for easier differentiation and filtering.
List of methods and properties
The following are the Node.jsconsolemodule's main methods and properties:
| Method/Property | Description | Output stream | Version introduced |
|---|---|---|---|
| console.log([data][, ...args]) | Print to stdout with a newline | stdout | 0.1.100 |
| console.error([data][, ...args]) | Print to stderr with a newline | stderr | 0.1.100 |
| console.warn([data][, ...args]) | Alias for console.error | stderr | 0.1.100 |
| console.info([data][, ...args]) | Alias for console.log | stdout | 0.1.100 |
| console.debug([data][, ...args]) | Print debug information to stdout | stdout | 8.0.0 |
| console.dir(obj[, options]) | Use util.inspect() on an object and print the result | stdout | 0.1.100 |
| console.time([label]) | Start a timer | - | 0.1.100 |
| console.timeEnd([label]) | Stop the timer and print the result | stdout | 0.1.100 |
| console.timeLog([label][, ...data]) | Print the current timer value | stdout | 10.7.0 |
| console.trace([message][, ...args]) | Print a stack trace to stderr | stderr | 0.1.100 |
| console.assert(value[, message][, ...args]) | If value is falsy, the assertion fails and message is printed | stderr | 0.1.100 |
| console.clear() | Attempt to clear the console | - | 8.3.0 |
| console.count([label]) | Count the number of calls to label | stdout | 8.3.0 |
| console.countReset([label]) | Reset the counter | stdout | 8.3.0 |
| console.group([...label]) | Indent subsequent output | stdout | 8.5.0 |
| console.groupEnd() | End the current indented group | stdout | 8.5.0 |
| console.table(tabularData[, properties]) | Print data in table form | stdout | 10.0.0 |
| console.dirxml(...data) | If supported, call console.log to print an XML/HTML tree | stdout | - |
Special properties
| Property | Description |
|---|---|
| console.stdout | Writable stream to standard output |
| console.stderr | Writable stream to standard error output |
Node.js's console module is a simple yet powerful debugging tool, providing a variety of methods from basic logging to advanced features such as timing and table output. Mastering the use of the console module can significantly improve development efficiency and debugging experience.
Node.js built-in modules