Hiprup

How do you read command-line arguments in Node.js?

Command-line arguments are accessed through process.argv — an array containing all arguments passed when running a Node script.

Structure of process.argv:

  • process.argv[0] — path to the Node executable

  • process.argv[1] — path to the script file

  • process.argv[2] onwards — actual user arguments

// node script.js hello world --port 3000

// Raw access
console.log(process.argv);
// [
//   '/usr/local/bin/node',
//   '/app/script.js',
//   'hello',
//   'world',
//   '--port',
//   '3000'
// ]

// Common pattern: skip first two elements
const args = process.argv.slice(2);
console.log(args); // ['hello', 'world', '--port', '3000']

// Simple flag parsing
const portIndex = args.indexOf('--port');
const port = portIndex !== -1 ? args[portIndex + 1] : 8080;

process.argv[0] is always the node binary path and process.argv[1] is the script path. By slicing from index 2, you get only the user-provided arguments.

The example also shows basic flag parsing by finding the index of '--port' and reading the next element as its value.

Know both the raw process.argv approach and mention that production CLIs use libraries like commander or yargs for robust argument parsing.