Programming

Node.js Command Line Arguments with process.argv - Examples

Pass and access Node.js command line arguments with process.argv. Examples for positional args, path resolution, validation, and when to use minimist or yargs.

1 answer 5 views

How do I pass command line arguments to a Node.js program and access them in my code?

I have a web server written in Node.js and I would like to launch it with a specific folder. I’m not sure how to access command line arguments in JavaScript. I’m running Node.js like this:

$ node server.js folder

Here server.js is my server code. According to the Node.js help documentation, this is possible:

$ node -h
Usage: node [options] script.js [arguments]

How would I access those arguments in JavaScript? I haven’t been able to find this information online.

To pass Node.js command line arguments, put them after the script name (for example node server.js folder) and read them from the built-in process.argv array. The first two entries are the Node.js executable and the script file path, so use process.argv.slice(2) to get the user-supplied arguments; for richer parsing use libraries like minimist, yargs, or command-line-args.


Contents


Accessing Node.js command line arguments with process.argv

Node.js exposes command line arguments via the global process.argv array. Indexes mean:

  • process.argv[0] — path to the Node.js executable (e.g., /usr/local/bin/node)
  • process.argv[1] — path to the script file (e.g., /home/me/project/server.js)
  • process.argv[2] and onward — the user-supplied arguments (the ones you passed after the script name)

So when you run:

bash
$ node server.js folder

process.argv might look like:

js
[
 "/usr/local/bin/node",
 "/full/path/to/server.js",
 "folder"
]

A common pattern is to drop the first two items and work with the rest:

js
const args = process.argv.slice(2); // ['folder']
const folder = args[0]; // 'folder'

Remember: every element in process.argv is a string. If you expect a number (port, timeout), convert it with parseInt() or Number().

See a concise explanation and examples on Stack Overflow and GeeksforGeeks for the same pattern: https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program-and-receive-them and https://www.geeksforgeeks.org/how-to-parse-command-line-arguments-in-node-js/.


Example: Node.js server — launching with a folder argument

Want to launch your server with a specific folder? Here’s a minimal example that reads the folder and an optional port:

server.js

js
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');

const [folder = 'public', port = '3000'] = process.argv.slice(2);
const root = path.resolve(process.cwd(), folder);
const PORT = parseInt(port, 10);

if (!fs.existsSync(root)) {
 console.error(`Folder "${root}" not found`);
 process.exit(1);
}

const server = http.createServer((req, res) => {
 const urlPath = req.url === '/' ? '/index.html' : req.url;
 const filePath = path.join(root, urlPath);

 fs.readFile(filePath, (err, data) => {
 if (err) {
 res.writeHead(404, {'Content-Type': 'text/plain'});
 res.end('Not found');
 return;
 }
 res.writeHead(200);
 res.end(data);
 });
});

server.listen(PORT, () => {
 console.log(`Serving ${root} on http://localhost:${PORT}`);
});

Run it like:

bash
$ node server.js ./public 8080
# or just:
$ node server.js my-folder

Notes:

  • Use process.cwd() to resolve relative folder names from where you ran the command (most intuitive for CLI users).
  • If you use npm run scripts, remember to pass args after --, e.g. npm run start -- my-folder.

DigitalOcean has a hands-on tutorial covering similar examples and patterns: https://www.digitalocean.com/community/tutorials/nodejs-command-line-arguments-node-scripts.


Parsing Node.js command line arguments (minimist, yargs, command-line-args)

For simple positional arguments process.argv.slice(2) is enough. If you want flags, aliases, defaults or help text, use a parser. Popular choices include minimist, yargs, and command-line-args.

minimist (tiny, easy)

bash
npm install minimist
js
const minimist = require('minimist');
const argv = minimist(process.argv.slice(2), {
 alias: { p: 'port', f: 'folder' },
 default: { port: 3000, folder: 'public' }
});

const folder = argv.folder; // supports --folder or -f
const port = Number(argv.port);

yargs (feature-rich, great for CLI apps)

bash
npm install yargs
js
const argv = require('yargs/yargs')(process.argv.slice(2))
 .option('port', { alias: 'p', type: 'number', default: 3000 })
 .option('folder', { alias: 'f', type: 'string', default: 'public' })
 .help()
 .argv;

const { folder, port } = argv;

command-line-args (another mature option — see its README): https://www.npmjs.com/package/command-line-args?activeTab=readme

Pick a library when you need:

  • named options (--port=8080, --folder ./public)
  • combined short flags (-p 8080)
  • automatic --help generation
    If your script is simple, though, process.argv.slice(2) keeps things tiny and dependency-free.

Tips, validation and common pitfalls for Node.js CLI

  • Slice off the first two items: don’t treat process.argv[0] and [1] as user arguments.
  • Parse numbers explicitly: const port = parseInt(argv, 10); otherwise "8080" stays a string.
  • Resolve paths: use path.resolve(process.cwd(), userPath) so ./public means what the user expects.
  • Validate inputs early and exit with a non-zero code on error: process.exit(1). That helps scripts and CI detect failures.
  • Spaces and quoting: on most shells you must quote paths with spaces: node server.js "My Folder". Windows command prompt rules differ.
  • When using npm run scripts, forward args with --, e.g. npm run start -- my-folder.
  • For production or complex CLIs use a parser (see above) and add a --help option.
  • Don’t confuse environment variables with arguments: use process.env for config that shouldn’t be typed every run; Node also recognizes NODE_OPTIONS and other CLI environment hooks (see Node.js CLI docs: https://nodejs.org/api/cli.html).
  • If you need POSIX-style behavior (subcommands, nested commands), look at yargs or commander.

For quick reference and more examples see these posts and docs: https://www.tutorialspoint.com/process-argv-method-in-node-js, https://sentry.io/answers/command-line-arguments-in-node/, and https://www.geeksforgeeks.org/node-js-process-argv-property/.


Sources


Conclusion

Passing Node.js command line arguments is simple: provide them after the script name and read them from process.argv (use process.argv.slice(2) for user-supplied values). For positional args this is enough; for flags, aliases, defaults and help text use a parser such as minimist, yargs or command-line-args. Good luck—now your server can start with the folder you choose.

Authors
Verified by moderation
Moderation
Node.js Command Line Arguments with process.argv - Examples