Nodejs Console Module
[Node.js Built-in Modules](#)
* * *
The `console` module is one of the most commonly used built-in modules in Node.js. It provides a simple debugging console, similar to the JavaScript `console` object in browsers. This module is primarily used to print information to standard output (stdout) and standard error (stderr), making it an essential tool for debugging and logging during development.
* * *
## Basic Usage of the console Module
### 1. Printing General Information
`console.log()` is the most commonly used method for printing general information:
## Example
console.log('Hello, Node.js!');
// Output: Hello, Node.js!
### 2. Printing Error Information
`console.error()` is used to print error messages, which by default are output to stderr:
## Example
console.error('This is an error message');
// Output (in red): This is an error message
### 3. Printing Warning Information
`console.warn()` is used to print warning messages:
## Example
console.warn('This is a warning message');
// Output (in yellow): This is a warning message
### 4. Printing Informational Messages
`console.info()` is similar to `console.log()` and is used to print informational messages:
## Example
console.info('This is an informational message');
// Output: This is an informational message
* * *
## Advanced Features of the console Module
### 1. Formatted Output
The console module supports formatted output similar to the C language printf() style:
## Example
const name ='Alice';
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 floating-point)
* `%i` - Integer
* `%f` - Floating-point number
* `%o` - Object
* `%j` - JSON
### 2. Timing Function
`console.time()` and `console.timeEnd()` can be used to measure code execution time:
## Example
console.time('array test');
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()` and `console.groupEnd()` can create collapsible message groups:
## Example
console.group('User Details');
console.log('Name: Alice');
console.log('Age: 25');
console.groupEnd();
### 4. Table Output
`console.table()` can output arrays or objects in table format:
## Example
const users =[
{ name:'Alice', age:25},
{ name:'Bob', age:30}
];
console.table(users);
### 5. Assertion Testing
`console.assert()` is used for simple assertion testing:
## Example
const x =5;
console.assert(x ===10,'x should be 10');
// Output when assertion is false: Assertion failed: x should be 10
* * *
## Configuration Options of the console Module
### 1. Custom Output Streams
You can create a custom Console instance specifying different output streams:
## Example
const{ Console }= require('console');
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 have colors:
## Example
console.log('x 1b[36m%sx 1b[0m','Cyan colored text');
Or use third-party libraries like `chalk` to simplify color control:
## Example
const chalk = require('chalk');
console.log(chalk.blue('Blue text'));
* * *
## Best Practices
1. **Production Environment Logging**: In production environments, it is recommended to use dedicated logging libraries like `winston` or `bunyan` instead of console.
2. **Avoid Overuse**: Use console only during development and debugging stages; remove unnecessary console statements from production code.
3. **Performance Considerations**: console.log is synchronous, so use it cautiously in performance-sensitive scenarios.
4. **Error Handling**: Use console.error to record error information for easy distinction and filtering.
* * *
## Method and Property List
Below are the main methods and properties of the Node.js `console` module:
| Method/Property | Description | Output Stream | Version Introduced |
| --- | --- | --- | --- |
| **console.log([, ...args])** | Prints to stdout with a newline | stdout | 0.1.100 |
| **console.error([, ...args])** | Prints to stderr with a newline | stderr | 0.1.100 |
| **console.warn([, ...args])** | Alias for console.error | stderr | 0.1.100 |
| **console.info([, ...args])** | Alias for console.log | stdout | 0.1.100 |
| **console.debug([, ...args])** | Prints debug information to stdout | stdout | 8.0.0 |
| **console.dir(obj[, options])** | Uses util.inspect() on the object and prints the result | stdout | 0.1.100 |
| **console.time()** | Starts a timer | - | 0.1.100 |
| **console.timeEnd()** | Stops a timer and prints the result | stdout | 0.1.100 |
| **console.timeLog([, ...data])** | Prints the current timer value | stdout | 10.7.0 |
| **console.trace([, ...args])** | Prints a stack trace to stderr | stderr | 0.1.100 |
| **console.assert(value[, message][, ...args])** | Asserts failure and prints message if value is falsy | stderr | 0.1.100 |
| **console.clear()** | Attempts to clear the console | - | 8.3.0 |
| **console.count()** | Counts the number of calls for a label | stdout | 8.3.0 |
| **console.countReset()** | Resets the counter | stdout | 8.3.0 |
| **console.group([...label])** | Indents subsequent output | stdout | 8.5.0 |
| **console.groupEnd()** | Ends the current indentation group | stdout | 8.5.0 |
| **console.table(tabularData[, properties])** | Prints data in tabular form | stdout | 10.0.0 |
| **console.dirxml(...data)** | If supported, calls console.log to print XML/HTML tree | stdout | - |
The Node.js console module is a simple yet powerful debugging tool, offering a variety of methods from basic logging to advanced features like timing and table output. Mastering the use of the console module can significantly improve development efficiency and debugging experience.
YouTip