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

← Node.js answers

process.argv holds the raw arguments (the first two entries are node and the script path). For flags, use the built-in util.parseArgs.

// node cli.js --port 8080 --verbose input.txt
import { parseArgs } from "node:util";
 
const { values, positionals } = parseArgs({
  options: {
    port: { type: "string", short: "p", default: "3000" },
    verbose: { type: "boolean", short: "v" },
  },
  allowPositionals: true,
});
 
console.log(values.port, values.verbose, positionals);
// "8080" true [ "input.txt" ]

Values come back as strings, so convert numbers yourself. For a larger tool with subcommands and generated help text, a library such as commander is worth the dependency.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required