Console in Node.js
Node.js, unlike client-side JavaScript, allows you to interact directly with your computer’s console (terminal). This makes it perfect for creating command-line tools, scripts, and interactive applications. This guide introduces beginners to using the console in Node.js applications.
The Node.js REPL
Before writing files, you can experiment with Node.js using the REPL (Read-Eval-Print Loop). It’s an interactive console where you can test JavaScript code immediately.
Starting the REPL
Open your terminal and type:
You’ll see a > prompt where you can type JavaScript:
> console.log('Hello, Node.js!')
Hello, Node.js!
undefined
> 2 + 2
4
> const name = 'Alice'
undefined
> `Hello, ${name}!`
'Hello, Alice!'
Exiting the REPL
To exit:
- Type
.exitand press Enter - Or press
Ctrl+Ctwice - Or press
Ctrl+D(on Mac/Linux)
REPL is Great for Learning
Use the REPL to test small pieces of code before adding them to your files. It’s the fastest way to experiment with JavaScript!
Console Output Methods
Node.js provides several methods for outputting information to the console.
Basic Logging
console.log() - Prints messages to the console:
console.log('Hello, World!');
console.log('Number:', 42);
console.log('Multiple', 'arguments', 'work', 'too');
console.error() - Outputs error messages (typically shown in red):
Displaying Structured Data
console.table() - Displays arrays and objects in a readable table format:
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
console.table(users);
// ┌──────────┬────────────┬─────┐
// │ (index) │ name │ age │
// ├──────────┼────────────┼─────┤
// │ 0 │ 'Alice' │ 25 │
// │ 1 │ 'Bob' │ 30 │
// │ 2 │ 'Charlie' │ 35 │
// └──────────┴────────────┴─────┘
console.dir() - Displays an object’s properties in a detailed format:
const person = {
name: 'Alice',
age: 25,
address: {
city: 'Copenhagen',
country: 'Denmark'
}
};
console.dir(person, { depth: null, colors: true });
Measuring Performance
console.time() and console.timeEnd() - Measure how long operations take:
console.time('loop');
for (let i = 0; i < 1000000; i++) {
// Some operation
}
console.timeEnd('loop');
// loop: 2.534ms
Command-Line Arguments
The simplest way to get input into your Node.js program is through command-line arguments using process.argv.
Understanding process.argv
process.argv is an array containing the command-line arguments:
Run it:
Output:
[
'/usr/local/bin/node', // [0] Path to Node.js
'/path/to/greet.js', // [1] Path to your script
'Alice', // [2] First argument
'Bob' // [3] Second argument
]
Simple Example
Run it:
Calculator Example
// calc.js
const num1 = parseFloat(process.argv[2]);
const num2 = parseFloat(process.argv[3]);
if (isNaN(num1) || isNaN(num2)) {
console.error('Please provide two numbers!');
process.exit(1);
}
console.log(`${num1} + ${num2} = ${num1 + num2}`);
Run it:
Reading Interactive User Input
For interactive programs where you ask questions and wait for answers, use the readline module.
Basic Readline Setup
// question.js
import readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What is your name? ', (name) => {
console.log(`Hello, ${name}!`);
rl.close();
});
Run it:
Important Notes
- The
readlinemodule must be imported using ES Modules syntax - Always call
rl.close()when done, or your program won’t exit - The callback function runs after the user enters their answer
Multiple Questions Example
// survey.js
import readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What is your name? ', (name) => {
rl.question('What is your favorite color? ', (color) => {
console.log(`${name}'s favorite color is ${color}!`);
rl.close();
});
});
Why the Nested Callbacks?
readline is asynchronous, meaning it doesn’t block your program while waiting for input. The callback function only runs after the user provides their answer. This is why questions are nested inside each other.
Example: Interactive Calculator
Here’s a complete example that asks for two numbers and adds them:
// add.js
import readline from 'readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter first number: ', (input1) => {
const num1 = parseFloat(input1);
rl.question('Enter second number: ', (input2) => {
const num2 = parseFloat(input2);
if (isNaN(num1) || isNaN(num2)) {
console.error('Invalid numbers!');
} else {
console.log(`${num1} + ${num2} = ${num1 + num2}`);
}
rl.close();
});
});
Run it:
Styling Console Output with Chalk
Chalk is a popular npm package that adds colors and styles to your console output, making it more readable and visually appealing.
Installing Chalk
First, ensure your project is set up for ES Modules. Your package.json should include:
Install Chalk:
Basic Usage
// colorful.js
import chalk from 'chalk';
console.log(chalk.blue('Hello in blue!'));
console.log(chalk.red('Error message in red'));
console.log(chalk.green('Success in green'));
Combining Styles
import chalk from 'chalk';
// Bold text
console.log(chalk.bold('Bold text'));
// Underlined text
console.log(chalk.underline('Underlined text'));
// Combining multiple styles
console.log(chalk.red.bold('Bold red text'));
console.log(chalk.blue.underline('Underlined blue text'));
// Background colors
console.log(chalk.bgYellow.black('Black text on yellow background'));
Custom Colors
import chalk from 'chalk';
// Using hex colors
console.log(chalk.hex('#FFA500')('Orange text'));
// Using RGB colors
console.log(chalk.rgb(255, 165, 0)('Orange text with RGB'));
Practical Example: Status Messages
// status.js
import chalk from 'chalk';
console.log(chalk.green('✓') + ' File saved successfully');
console.log(chalk.red('✗') + ' Failed to load data');
console.log(chalk.yellow('⚠') + ' Warning: File is large');
console.log(chalk.blue('ℹ') + ' Processing...');
Enhanced Calculator with Chalk
// calc-colorful.js
import readline from 'readline';
import chalk from 'chalk';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log(chalk.blue.bold('=== Calculator ===\n'));
rl.question(chalk.cyan('Enter first number: '), (input1) => {
const num1 = parseFloat(input1);
rl.question(chalk.cyan('Enter second number: '), (input2) => {
const num2 = parseFloat(input2);
if (isNaN(num1) || isNaN(num2)) {
console.log(chalk.red('✗ Invalid numbers!'));
} else {
const result = num1 + num2;
console.log(chalk.green(`✓ ${num1} + ${num2} = ${chalk.bold(result)}`));
}
rl.close();
});
});
When to Use Chalk
Chalk is great for:
- Making error messages stand out in red
- Highlighting success messages in green
- Creating visual separators in output
- Building user-friendly CLI tools
Remember that styling is primarily for development and may not work in all environments.