- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Console
In Node.js, the console object is a global utility that provides a simple way to write to standard output (stdout) and standard error (stderr). While it might seem basic, it is the primary tool for real-time debugging, performance monitoring, and providing feedback to the developer during the execution of a script. Because it is a global object, you don't need to use require() or import to use it—it's available in every file by default.
console.log is synchronous when the destination is a terminal or a file, but can be asynchronous in other scenarios. For high-performance production apps, consider using a dedicated logging library like Winston or Pino.
Key Features of Console
- Logging Levels: Node.js supports various logging levels like
log,info,warn, anderror, helping you categorize the importance of messages. - Formatted Output: It supports string substitution (like
%sfor strings and%dfor numbers) and template literals for clean code. - Integrated Debugging: Tools like
console.trace()andconsole.time()provide built-in ways to profile performance and track function execution paths without extra dependencies.
Common Console Methods
1. console.log()
The log() method prints general informational messages to stdout. It is the go-to tool for checking variable values or confirming that a specific block of code has been reached.
// Basic logging
console.log('Server started on port 3000');
// Logging multiple values
const dbName = 'Production_DB';
console.log('Connecting to:', dbName, '...Success!');
Output:
Server started on port 3000
Connecting to: Production_DB ...Success!
console.log(`User ${id} has logged in.`);
2. console.warn()
The warn() method is used to highlight potential issues that aren't critical enough to stop the application. In many terminal environments, these messages are directed to stderr rather than stdout.
const apiVersion = 'v1';
if (apiVersion === 'v1') {
console.warn('Warning: API v1 is deprecated. Please migrate to v2.');
}
Output:
Warning: API v1 is deprecated. Please migrate to v2.
warn and error messages usually end up in the error log file, not the standard output file.
3. console.error()
The error() method is specifically for reporting failures, caught exceptions, or critical logic errors. This writes to the stderr stream, allowing developers to filter out "noise" and see only what went wrong.
try {
throw new Error('Database connection failed!');
} catch (err) {
console.error('Error occurred:', err.message);
}
Output:
Error occurred: Database connection failed!
console.log() for errors. Always use console.error() for actual failures so that monitoring tools (like PM2 or Datadog) can properly flag the issue.
4. console.table()
When working with arrays of objects or complex data structures, console.log() can become hard to read. The table() method renders your data as a neat, readable table.
const users = [
{ name: 'Alice', age: 30, role: 'Admin' },
{ name: 'Bob', age: 25, role: 'User' }
];
console.table(users);
Output:
console.table() as an array of strings to limit which columns are displayed: console.table(users, ['name']);.
5. console.time() and console.timeEnd()
If you need to check how long a specific operation takes (like an API call or a heavy loop), these methods act as a stopwatch. You give the timer a label, and Node.js will calculate the duration between the start and end calls.
console.time('DataProcessing');
// Simulating a heavy operation
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
console.timeEnd('DataProcessing');
Output:
DataProcessing: 4.567ms
time() and timeEnd(). If the labels don't match, the timer won't stop correctly and may throw a warning.
6. console.trace()
When working with deeply nested functions or complex asynchronous callbacks, it's often hard to tell exactly "how" you reached a certain point in the code. console.trace() prints the current stack trace, showing the file path and line numbers of every function call leading up to the current line.
function checkPermissions() {
console.trace('Tracing permission check...');
}
function processOrder() {
checkPermissions();
}
processOrder();
Output:
Tracing permission check...
at checkPermissions (/app/index.js:2:11)
at processOrder (/app/index.js:6:3)
at Object.<anonymous> (/app/index.js:9:1)
7. console.assert()
The assert() method is a simple way to verify conditions. If the condition passed to it is false, it logs the message. If the condition is true, nothing happens. Note that unlike some testing frameworks, console.assert() in Node.js does not stop the execution of the program.
const userRole = 'guest';
console.assert(userRole === 'admin', 'Access Denied: User is not an admin');
Output:
Assertion failed: Access Denied: User is not an admin
console.assert() behaves differently in Node.js than in some browsers. In Node, it prints "Assertion failed" followed by your message, but it will not throw an AssertionError that crashes the script.
Summary
The console object is more than just a way to print text; it is a versatile diagnostic suite built directly into the Node.js runtime. By using console.table() for data visualization, console.time() for performance benchmarks, and console.error() for proper stream management, you can create much more maintainable and debuggable applications. As your project grows, remember to clean up unnecessary logs to keep your terminal output clean and relevant.
eslint-plugin-no-console or a logger with environment-based levels to ensure your production logs aren't cluttered with "debug" messages that could leak sensitive information.