Command Line Tools
Node.js is a great fit for command line tools, the small programs you run in a terminal. A tool can read what you type, take arguments like --name Ada, and print results to the screen. Everything you need is built in, with no extra packages, which makes this the fastest way to feel what Node.js does outside the browser.
Arguments are the words you type after a command, like node greet.js Ada. They arrive in a built-in array called process.argv. The first two entries are always the same: the path to Node.js and the path to your script. Everything after index 2 is your own input. Reading arguments is how tools learn what to do.
When you need to ask a question and wait for an answer, the readline module handles it. It reads a line of typed input and hands it to a callback. This is the building block for interactive tools: a prompt, an answer, a loop back to the next question. Combined with arguments, you can build tools that both take options and ask follow-ups.
Reading arguments with process.argv
process.argv is an array. Index 0 is the Node.js executable, index 1 is your script, and index 2 onward is what the user typed. Slice off the first two and you have the real input. A typical tool checks how many arguments were given and prints a message when the user forgot them.
// run: node greet.js Ada
const args = process.argv.slice(2);
const name = args[0] || "world";
console.log("Hello, " + name + "!"); // Hello, Ada!
Asking for input with readline
readline reads a line from the terminal. Create the interface, ask a question, and use the answer in the callback. Because input is async, the rest of your logic has to run inside that callback or after an await.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name? ", (answer) => {
console.log("Hi, " + answer + "!");
rl.close(); // stop reading, let the program exit
});
Exit codes and errors
A script can end with a code that other programs read. process.exit(0) means success, and process.exit(1) means an error happened. Printing to process.stderr separates error text from normal output, which matters when a tool is piped into another command.
if (!args[0]) {
console.error("Usage: node tool.js <name>");
process.exit(1); // tell the caller something failed
}
console.log("OK");
process.exit(0);
Syntax
# greet.js
const name = process.argv[2] || "world";
console.log("Hello, " + name + "!");
# run it:
# node greet.js Ada
# Hello, Ada!
process.argv[0] Is Node, [1] Is File
process.argv[0] is node binary, [1] is script path — your args start at [2].
const args = process.argv.slice(2)
Good to know
- process.argv holds your arguments; slice off the first two entries.
- The readline module reads typed input from the terminal.
- process.exit(0) means success, process.exit(1) means an error.
- Print errors to stderr so pipes and logs stay clean.