How to read command-line arguments in Node.js
Short answer
process.argv is an array: the path to node, the path to the script, and then your arguments. Skip the first two. For the command node app.js input.txt:
const args = process.argv.slice(2);
console.log(args);
console.log('file:', args[0]);Output:
[ 'input.txt' ]
file: input.txtOptions
parseArgs() from node:util understands options like --verbose and --out=report.txt:
import { parseArgs } from 'node:util';
const { values, positionals } = parseArgs({
args: ['input.txt', '--out=report.txt', '--verbose'],
options: {
out: { type: 'string', default: 'result.txt' },
verbose: { type: 'boolean', short: 'v' },
},
allowPositionals: true,
});
console.log(positionals, values.out, values.verbose);Output:
[ 'input.txt' ] report.txt trueWithout the args option, parseArgs() reads the real process.argv. Here the arguments are passed explicitly to show the result.
Common mistake
All arguments are strings, even numbers. And if the user did not pass an argument, it is undefined, so check it:
const count = process.argv[3];
if (count === undefined) {
console.log('Usage: node app.js <file> <count>');
} else {
console.log(Number(count) + 1);
}Output:
Usage: node app.js <file> <count>Functions used in this recipe
- Array.prototype.slice — Returns part of an array.