Limited Offer
60% OFF on all plans!

Console Input & Output in Node.js

A beginner-friendly Node.js tutorial on how to print output in the terminal and take user input (text + numbers) using `console`, `process.stdout`, `process.argv`, and `readline`.

Console Output Basics

Console output means showing text on the terminal screen. Node.js provides simple built-in functions like `console.log()` to print messages and values. These are extremely useful for debugging and building CLI apps.

1. console.log() (Normal Output)

Use this when you want to print something and automatically go to the next line. Every `console.log()` ends with a newline.

2. Printing Variables (Template Literals)

Use template literals (backticks ` `` ` ) to print values inside strings using `` `${}` ``.

3. console.warn() and console.error()

These are used when you want to clearly show warnings or errors. They behave like `console.log()` but semantically mean something important.

Printing Without Newline (process.stdout)

Normally `console.log()` always adds a newline. But for CLI tools, sometimes you want to print progress like: `Loading...` and keep printing on the same line. For that, use `process.stdout.write()`.

1. process.stdout.write() (No Newline)

This prints exactly what you give it — without adding a newline automatically.

2. Creating a Simple Progress Effect

Using `setInterval()` to print dots every few milliseconds (like real CLI tools).

Formatted Console Output

Many CLI programs print clean tables. To align columns nicely, we use padding. In JavaScript: - `padStart()` = padLeft - `padEnd()` = padRight This ensures each column has fixed width.

1. padStart() and padEnd() Basics

`padStart(width, char)` adds extra chars on the left. `padEnd(width, char)` adds on right.

2. Print a Simple Table (Aligned Columns)

This prints rows in a fixed-width layout so everything looks clean.

Console Input (Reading User Data)

Console input means the user can type something in terminal and your program reads it. Node.js supports: 1) `process.argv` (fastest, used in commands) 2) `readline` (interactive input like a form)

1. process.argv (Command-Line Arguments)

Example: user runs `node app.js John 22` and your code reads those values.

2. readline (Interactive Input)

The program asks a question and waits for user input.

3. Scan a Number (Single Number Input)

Input from readline is ALWAYS string. Convert it to number and validate.

4. Scan Multiple Numbers (Space Separated)

Common in CLI: user types `10 20 30`. We split and convert them.