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

$ node server.js folder

here server.js is my server code. Node.js help says this is possible:

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

How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.

26 Answers 26

up vote 2549 down vote accepted

Standard Method (no library)

The arguments are stored in process.argv

Here are the node docs on handling command line args:


// print process.argv
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);

This will generate:

$ node process-2.js one two=three four
0: node
2: one
3: two=three
4: four
  • 5
    What should I type into the command prompt to run a node.js script with command-line arguments? – Anderson Green Oct 16 '12 at 0:58
  • 7
    UPDATE: I found the answer to the above question. stackoverflow.com/questions/12925802/… – Anderson Green Oct 17 '12 at 1:30
  • 2
    Minimist is a great and simple argument parser – Guilherme Nagatomo May 22 '14 at 2:04
  • 2
    You can also access a single argument when you know its position: process.argv[n] where n is the zero-based index – Luca Steeb Feb 1 '15 at 15:12
  • 2
    the 2nd element (process.argv[1]) may be or may be not js file. node command syntax is node [options] [ -e script | script.js ] [arguments] or node debug script.js [arguments]. for example: node --harmony script.js balala or node --no-deprecation --enable-ssl2 script.js balala , we can use process.execArgv with process.argv – cuixiping Jan 7 '16 at 12:43

To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:

var args = process.argv.slice(2);

Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.

  • 6
    Thanks Jaseem. Would love to see where that's written in the future spec. It would break so many js libraries... – Mauvis Ledford Jun 4 '12 at 0:21
  • 6
    Just a note that I wrote this answer 4 years ago and the code I am running is still running 100% fine today. Still keeping up to date with the latest versions of node and still zero problems: It's just a simple shell script guys. Not part of a big global object full of JS libraries. I still stand behind my answer today. I will give another update in 4 more years. – Mauvis Ledford Mar 5 '15 at 1:18
  • 4
    @MauvisLedford Lol I'd call that stubborn. args is both shorter and does not collide with built-ins. What's not to like? Just say 'Ah good tip I did not realize that' and be done with it :) – Stijn de Witt Jan 2 '16 at 16:44
  • 39
    var args = process.argv.splice(process.execArgv.length + 2); //because there are exceptions of node command usage, for example: node --harmony script.js balala. see process.execArgv – cuixiping Jan 7 '16 at 12:50
  • 24
    @cuixiping but the execArgv are not in argv so the 2 is enough – Tommi Kyntola Mar 30 '16 at 8:51

The up-to-date right answer for this it to use the minimist library. We used to use node-optimist but it has since been deprecated.

Here is an example of how to use it taken straight from the minimist documentation:



$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }


$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
  x: 3,
  y: 4,
  n: 5,
  a: true,
  b: true,
  c: true,
  beep: 'boop' }
  • 22
    Actually, this solution is more helpful for developing command line tool with more flags and arguments, and should be upvoted more IMHO. – JK ABC Feb 6 '15 at 3:15
  • 2
    Imo, this is a more simple alternative to npmjs.com/package/command-line-args – klodoma Nov 26 '15 at 11:44
  • 3
    @JKABC I would not call this the most correct answer, as the OP just asks to access trivial command line information. But I agree that both minimist and command-line-args are very useful if you are planning to extend your CLI. – Justus Romijn Sep 10 '17 at 19:22
  • 2
    I wonder why the '-n5' doesn't produce 'n5: true' - that would make sense to me. – Max Waterman Feb 12 at 12:11
  • 6
    @MaxWaterman: because options that start with a single dash are only supposed to a single character. Anything that follows a single char option is taken as an argument for the option (no space required). Starting the option with two dashes (i.e. --n5) should produce 'n5: true'. This is fairly standard behaviour for most Unix command line tools (but not all unfortunately). – Menno Smits Mar 15 at 22:34

2018 answer based on current trends in the wild:

Vanilla javascript argument parsing:

const args = process.argv;

This returns:

$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']

Official docs

Most used NPM packages for argument parsing:

Minimist: For minimal argument parsing.

Commander.js: Most adopted module for argument parsing.

Meow: Lighter alternative to Commander.js

Yargs: More sophisticated argument parsing (heavy).

Vorpal.js: Mature / interactive command-line applications with argument parsing.

  • 49
    "$ npm install -g yargs" yielded 1.9 MB of JavaScript code. When is this madness going to end when an argv parser library needs two megabytes of code? Increased attack surface, wasted RAM etc... – joonas.fi Oct 13 '16 at 17:21
  • 5
    Yargs is a larger tool that also happens to parse command line arguments. No madness, just lack of information. If you want something lighter, use the raw JS, Meow or Minimist. – dthree Oct 13 '16 at 21:58
  • nconf is missing – Michael Mar 30 '17 at 21:36
  • "$ npm i yargs" -> 800 KB here, i guess package owners finally learned to ignore irrelevant files. Anyway, still big for silly projects, but small when you need robustness and on larger projects you already have dependencies.. – Andre Figueiredo Jan 31 at 1:10
  • I have created a package, called wily-cli, with the goal of making a more powerful, more customizable, and easier to use tool than the big names listed. For those of you that are interested, it's only 94.6 KB upon installation – Jason Mar 2 at 19:12

Optimist (node-optimist)

Check out optimist library, it is much better than parsing command line options by hand.


Optimist is deprecated. Try yargs which is an active fork of optimist.

Several great answers here, but it all seems very complex. This is very similar to how bash scripts access argument values and it's already provided standard with node.js as MooGoo pointed out. (Just to make it understandable to somebody that's new to node.js)


$ node yourscript.js banana monkey

var program_name = process.argv[0]; //value will be "node"
var script_path = process.argv[1]; //value will be "yourscript.js"
var first_value = process.argv[2]; //value will be "banana"
var second_value = process.argv[3]; //value will be "monkey"


Works great for defining your options, actions, and arguments. It also generates the help pages for you.


Works great for getting input from the user, if you like the callback approach.


Works great for getting input from the user, if you like the generator approach.

  • 21
    @Evan Carroll please don't edit my answer to promote a library I don't use stackoverflow.com/posts/7483600/revisions especially because of a missing feature you're after, such opinions should be saved for comments or pull requests to the module authors, not edits to other people's answers. – balupton Nov 11 '13 at 1:56
  • Commander.js really helped me out. Other libraries would not work with the nexe compiler but this one does the trick. If you want to get args when using nexe, be sure to pass -f to the nexe compiler. – pierce.jason Jul 21 '14 at 16:36

Stdio Library

The easiest way to parse command-line arguments in NodeJS is using the stdio module. Inspired by UNIX getopt utility, it is as trivial as follows:

var stdio = require('stdio');
var ops = stdio.getopt({
    'check': {key: 'c', args: 2, description: 'What this option means'},
    'map': {key: 'm', description: 'Another description'},
    'kaka': {args: 1, mandatory: true},
    'ooo': {key: 'o'}

If you run the previous code with this command:

node <your_script.js> -c 23 45 --map -k 23 file1 file2

Then ops object will be as follows:

{ check: [ '23', '45' ],
  args: [ 'file1', 'file2' ],
  map: true,
  kaka: '23' }

So you can use it as you want. For instance:

if (ops.kaka && ops.check) {
    console.log(ops.kaka + ops.check[0]);

Grouped options are also supported, so you can write -om instead of -o -m.

Furthermore, stdio can generate a help/usage output automatically. If you call ops.printHelp() you'll get the following:

USAGE: node something.js [--check <ARG1> <ARG2>] [--kaka] [--ooo] [--map]
  -c, --check <ARG1> <ARG2>   What this option means (mandatory)
  -k, --kaka                  (mandatory)
  --map                       Another description
  -o, --ooo

The previous message is shown also if a mandatory option is not given (preceded by the error message) or if it is mispecified (for instance, if you specify a single arg for an option and it needs 2).

You can install stdio module using NPM:

npm install stdio
  • 2
    As per SO's TOS, it's worth mentioning @sgmonda is the sole maintainer of the module ;) Nice little module, though. Definitely useful. – Qix Jan 27 '14 at 5:29
  • Indeed useful, though the most recent update was Dec 30, 2014. May not be as well maintained as some other packages. – fearless_fool Dec 21 '16 at 0:10
  • nice lib! tks! altough it is witthout recent updates .. It have enough good functionality – Pablo Ezequiel Apr 13 at 1:52

If your script is called myScript.js and you want to pass the first and last name, 'Sean Worthington', as arguments like below:

node myScript.js Sean Worthington

Then within your script you write:

var firstName = process.argv[2]; // Will be set to 'Sean'
var lastName = process.argv[3]; // Will be set to 'Worthington'

command-line-args is worth a look!

You can set options using the main notation standards (learn more). These commands are all equivalent, setting the same values:

$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js

To access the values, first create a list of option definitions describing the options your application accepts. The type property is a setter function (the value supplied is passed through this), giving you full control over the value received.

const optionDefinitions = [
  { name: 'verbose', alias: 'v', type: Boolean },
  { name: 'src', type: String, multiple: true, defaultOption: true },
  { name: 'timeout', alias: 't', type: Number }

Next, parse the options using commandLineArgs():

const options = commandLineArgs(optionDefinitions)

options now looks like this:

  src: [
  verbose: true,
  timeout: 1000

Advanced usage

Beside the above typical usage, you can configure command-line-args to accept more advanced syntax forms.

Command-based syntax (git style) in the form:

$ executable <command> [options]

For example.

$ git commit --squash -m "This is my commit message"

Command and sub-command syntax (docker style) in the form:

$ executable <command> [options] <sub-command> [options]

For example.

$ docker run --detached --image centos bash -c yum install -y httpd

Usage guide generation

A usage guide (typically printed when --help is set) can be generated using command-line-usage. See the examples below and read the documentation for instructions how to create them.

A typical usage guide example.


The polymer-cli usage guide is a good real-life example.


Further Reading

There is plenty more to learn, please see the wiki for examples and documentation.

  • @Lloyd this is connected to issue already risen - here. Webstorm passes some additional arguments. – kboom Jan 28 '17 at 18:07
  • @kboom that issue was resolved by the partial and stopAtFirstUnknown options. See the docs. – Lloyd Jan 28 at 19:39

There's an app for that. Well, module. Well, more than one, probably hundreds.

Yargs is one of the fun ones, its docs are cool to read.

Here's an example from the github/npm page:

#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);

Output is here (it reads options with dashes etc, short and long, numeric etc).

$ ./nonopt.js -x 6.82 -y 3.35 rum
[ 'rum' ] 
$ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
[ 'me hearties', 'yo', 'ho' ]

It's probably a good idea to manage your configuration in a centralized manner using something like nconf https://github.com/flatiron/nconf

It helps you work with configuration files, environment variables, command-line arguments.

Passing,parsing arguments is an easy process. Node provides you with the process.argv property, which is an array of strings, which are the arguments that were used when Node was invoked. The first entry of the array is the Node executable, and the second entry is the name of your script.

If you run script with below atguments

$ node args.js arg1 arg2

File : args.js


You will get array like


whithout librairies: using Array.prototype.reduce()

const args = process.argv.slice(2).reduce((acc, arg) => {

    let [k, v = true] = arg.split('=')
    acc[k] = v
    return acc

}, {})

for this command node index.js count=2 print debug=false msg=hi

console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }


we can change

    acc[k] = v

by (much longer)

    let [k, v] = arg.split('=')
    acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v

to auto parse Boolean & Number

console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
  • Your longer version has a problem with strings that contain dots. – berliner Jan 5 at 19:33
  • Clever solution! What if I want to support both count and c command line options (c as an alias/shorcut for count)? – Alex Vang Apr 10 at 10:48

Here's my 0-dep solution for named arguments:

const args = process.argv
    .map(arg => arg.split('='))
    .reduce((args, [value, key]) => {
        args[value] = key;
        return args;
    }, {});



$ node test.js foo=bar fizz=buzz

Note: Naturally this will fail when the argument contains a =. This is only for very simple usage.

npm install ps-grab

If you want to run something like this :

node greeting.js --user Abdennour --website http://abdennoor.com 


var grab=require('ps-grab');
grab('--username') // return 'Abdennour'
grab('--action') // return 'http://abdennoor.com'

Or something like :

node vbox.js -OS redhat -VM template-12332 ;


var grab=require('ps-grab');
grab('-OS') // return 'redhat'
grab('-VM') // return 'template-12332'
  • This repo is no longer available on github. – steadweb Feb 3 '17 at 17:37

You can parse all arguments and check if they exist.

file: parse-cli-arguments.js:

module.exports = function(requiredArguments){
    var arguments = {};

    for (var index = 0; index < process.argv.length; index++) {
        var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
            matches = re.exec(process.argv[index]);

        if(matches !== null) {
            arguments[matches[1]] = matches[2];

    for (var index = 0; index < requiredArguments.length; index++) {
        if (arguments[requiredArguments[index]] === undefined) {
            throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);

    return arguments;

Than just do:

var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);

You can reach command line arguments using system.args. And i use the solution below to parse arguments into an object, so i can get which one i want by name.

var system = require('system');

var args = {};
system.args.map(function(x){return x.split("=")})

now you don't need to know the index of the argument. use it like args.whatever

Note: you should use named arguments like file.js x=1 y=2 to use this solution.


for(var i=0;i<process.argv.length;i++){


nodemon app.js "arg1" "arg2" "arg3"


0 'C:\\Program Files\\nodejs\\node.exe'
1 'C:\\Users\\Nouman\\Desktop\\Node\\camer nodejs\\proj.js'
2 'arg1' your first argument you passed.
3 'arg2' your second argument you passed.
4 'arg3' your third argument you passed.


0 : The directory of node.exe in your maching (C:\Program Files\nodejs\node.exe')

1 : The directory of your project file. (proj.js)

2 : Your first argument to node (arg1)

3 : Your second argument to node (arg2)

4 : Your third argument to node (arg3)

your actual arguments start form 2nd index of argv array, that is process.argv[2].

Without libraries

If you want to do this in vanilla JS/ES6 you can use the following solution

worked only in NodeJS > 6

const args = process.argv
  .map((val, i)=>{
    let object = {};
    let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
    let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
      object[val] = true;
      return object;
    } else {
      object[prop[1]] = value[1] ;
      return object
  .reduce((obj, item) => {
    let prop = Object.keys(item)[0];
    obj[prop] = item[prop];
    return obj;
  }, {});

And this command

node index.js host=http://google.com port=8080 production

will produce the following result

console.log(args);//{ host:'http://google.com',port:'8080',production:true }

p.s. Please correct the code in map and reduce function if you find more elegant solution, thanks ;)

  • i agree, but it could be shorter no ? let args = process.argv.slice(2).reduce((acc, arg) => { let [k, v] = arg.split('=') acc[k] = v return acc }, {}) – Joseph Merdrignac Oct 13 '17 at 12:23

The simplest way of retrieving arguments in Node.js is via the process.argv array. This is a global object that you can use without importing any additional libraries to use it. You simply need to pass arguments to a Node.js application, just like we showed earlier, and these arguments can be accessed within the application via the process.argv array.

The first element of the process.argv array will always be a file system path pointing to the node executable. The second element is the name of the JavaScript file that is being executed. And the third element is the first argument that was actually passed by the user.

'use strict';

for (let j = 0; j < process.argv.length; j++) {  
    console.log(j + ' -> ' + (process.argv[j]));

All this script does is loop through the process.argv array and prints the indexes, along with the elements stored in those indexes. It's very useful for debugging if you ever question what arguments you're receiving, and in what order.

You can also use libraries like yargs for working with commnadline arguments.

as stated in the node docs The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.

For example, assuming the following script for process-args.js:

// print process.argv
process.argv.forEach((val, index) => {
   console.log(`${index}: ${val}`);

Launching the Node.js process as:

 $ node process-args.js one two=three four

Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four

Most of the people have given good answers. I would also like to contribute something here. I am providing the answer using lodash library to iterate through all command line arguments we pass while starting the app:

// Lodash library
const _ = require('lodash');

// Function that goes through each CommandLine Arguments and prints it to the console.
const runApp = () => {
    _.map(process.argv, (arg) => {

// Calling the function.

To run above code just run following commands:

npm install
node index.js xyz abc 123 456

The result will be:


process.argv is your friend, capturing command line args is natively supported in Node JS. See example below::

process.argv.forEach((val, index) => {

You can also use yargs package it will make thing a lot easier! here you go :) Yargs

A simple snippet if any need it:

var fs = require('fs'), objMod = {};

process.argv.slice(2).map(function(y, i) {
  y = y.split('=');
  if (y[0] && y[1]) objMod[y[0]] = y[1];
  else console.log('Error in argument number ' + (i+1));
  • Why do you use require('fs')? – barwnikk Mar 22 at 20:21

Your Answer

