Node.js Basics
Node.js Command Line Arguments
process.argv holds the command-line arguments as an array: the Node executable, the script path, then anything the user typed. Node also ships a built-in parseArgs helper for flags.
What is Command Line Arguments in Node.js?
process.argv holds the command-line arguments as an array: the Node executable, the script path, then anything the user typed. Node also ships a built-in parseArgs helper for flags.
Command Line Arguments example
JavaScript
// node backup.js --out ./dump --verbose
console.log(process.argv.slice(2)); // ['--out', './dump', '--verbose']
import { parseArgs } from 'node:util';
const { values } = parseArgs({
options: {
out: { type: 'string', short: 'o', default: './dump' },
verbose: { type: 'boolean', short: 'v', default: false },
},
});
console.log(values.out, values.verbose);Key points to remember
- The first two entries are always the Node binary and the script path.
- parseArgs is built in — no dependency needed for simple CLIs.
- Use commander or yargs for complex tools with subcommands and help text.
- A "bin" entry in package.json makes a script installable as a command.
Node.js Command Line Arguments— Interview Questions & FAQs
How do I read command line arguments in Node.js?+
process.argv.slice(2) gives the user-supplied arguments. For flags, node:util’s parseArgs handles types and defaults without any dependency.
