3085

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.

2
  • It's probably a good idea to manage your configuration in a centralized manner using something like nconf github.com/flatiron/nconf It helps you work with configuration files, environment variables, command-line arguments.
    – 250R
    Commented May 26, 2012 at 0:10
  • And here's configvention, my own, minimal, readonly interface for nconf.
    – Joel Purra
    Commented Jan 26, 2014 at 12:02

41 Answers 41

3716

Standard Method (no library)

The arguments are stored in process.argv

Here are the node docs on handling command line args:

process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

// 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
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
6
  • 34
    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
    Commented Jan 7, 2016 at 12:43
  • 2
    nodejs.org/docs/latest/api/process.html#processexecargv
    – Kid
    Commented Oct 11, 2022 at 12:21
  • 6
    Per node.js document, process.argv doesn't return those node.js-specific flags. like --harmony in your example
    – Kid
    Commented Oct 11, 2022 at 12:22
  • For some reason that code did not output anything in TypeScript with tsx. The arguments are there though in process.argv.
    – Slion
    Commented Jun 28, 2023 at 7:41
  • 7
    2023, new to the node runtime, have to walk through these answers, many claiming to be 'the new way', in 2016,2018.. The TLDR from 2023 looks like: this answer has always been right, there's just 2 gotchas in that you have two args you need to ignore; and it doesn't capture args entered into/before the node.exe, like --harmony node.exe - but it's okay, you can get those somewhere else. The other notable answers are libraries that parse the input args more nicely and extractable. And minimist was one, that stopped being supported, but now it seems is alive again, in a different repo.
    – zola25
    Commented Aug 16, 2023 at 4:30
995

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.

3
  • While this answers the question in a simple way, note that this method doesn't support flags and requires that the arguments be passed in a strict order.
    – Marcin
    Commented Jul 27, 2022 at 10:17
  • @M-Cat: try this: for (let i=2; i<argv.length; i++) { switch (argv[i]) { case "--foo": foo=argv[++i]; break; case "--bar": bar=argv[++i]; break; default: throw new Error("unknown arg"); } } Commented Oct 2, 2022 at 4:29
  • @Marcin No, it does support flags and arguments being passed in any order. It all depends on how you process args. You could for instance parse it with minimist: require('minimist')(process.argv.slice(2))
    – Erik B
    Commented Mar 11 at 13:45
509

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:

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);

-

$ 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' }
4
  • 55
    Actually, this solution is more helpful for developing command line tool with more flags and arguments, and should be upvoted more IMHO.
    – JK ABC
    Commented Feb 6, 2015 at 3:15
  • 9
    If you're going to use this answer, consider using the more active fork, minimist-lite as the former is abandoned. The "up-to-date right answer" would be to use process.argv.slice(2) which is the answer for the actual question... Commented Jan 24, 2022 at 21:32
  • 3
    That library looks useful, especially if you need to parse the arguments. However the "up-to-date right answer" is almost never to introduce an additional third-party library to do something that's already built-in. process.argv.slice(2) gets the job done without any additional libraries.
    – aroth
    Commented Oct 18, 2023 at 5:10
  • minimist is no longer abandoned and is quite active, fwiw.
    – LJHarb
    Commented Mar 13 at 5:51
443

2018 answer based on current trends in the wild:


Vanilla javascript argument parsing:

const args = process.argv;
console.log(args);

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.

3
  • 151
    "$ 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
    Commented Oct 13, 2016 at 17:21
  • simple way to select custom arg: const list_arg = process.argv.filter((arg) => (['-list', '-l'].includes(arg))).toString(); Commented Nov 23, 2021 at 15:40
  • 1
    Thanks for the list of good packages! Adding meow unfortunately crashes esrun (!!), but minimist worked fine.
    – berkus
    Commented Jan 18 at 9:26
137

Optimist (node-optimist)

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

Update

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

1
135

No Libs with Flags Formatted into a Simple Object

const getArgs = () =>
  process.argv.reduce((args, arg) => {
    // long arg
    if (arg.slice(0, 2) === "--") {
      const longArg = arg.split("=");
      const longArgFlag = longArg[0].slice(2);
      const longArgValue = longArg.length > 1 ? longArg[1] : true;
      args[longArgFlag] = longArgValue;
    }
    // flags
    else if (arg[0] === "-") {
      const flags = arg.slice(1).split("");
      flags.forEach((flag) => {
        args[flag] = true;
      });
    }
    return args;
  }, {});

const args = getArgs();
console.log(args);

Examples

Simple

input

node test.js -D --name=Hello

output

{ D: true, name: 'Hello' }

Real World

input

node config/build.js -lHRs --ip=$HOST --port=$PORT --env=dev

output

{ 
  l: true,
  H: true,
  R: true,
  s: true,
  ip: '127.0.0.1',
  port: '8080',
  env: 'dev'
}
1
  • .slice(2, process.argv.length) isn't the second arg redundant? .slice() goes to the end of string by default.
    – hastrb
    Commented Nov 12, 2021 at 6:54
133

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)

Example:

$ 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"
0
90

Commander.js

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

Promptly

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

Co-Prompt

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

1
  • 34
    @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
    Commented Nov 11, 2013 at 1:56
84

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, required: 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
6
  • Strange, I get requires 1 arguments for an argument that I've set required: false. I even tried this with version 2 of the library. Commented Jan 24, 2022 at 4:58
  • ops.printHelp() did not work for me. maybe it was true for old versions?
    – Nir O.
    Commented Dec 17, 2022 at 21:42
  • @NirO. isn't the automatic --help behavior enough in your case? Help must be printed.
    – sgmonda
    Commented Dec 18, 2022 at 13:15
  • the fact that printHelp() doesn't work just shades a light on the fact that this post may be outdated and other readers should pay attention that the library may no longer behave as described here, that's all. I think that "required" behavior is also different than the post but I moved on
    – Nir O.
    Commented Dec 18, 2022 at 19:52
  • Where we can put the ops in <your_script.js> ? Commented Mar 6, 2023 at 23:23
62

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'
0
55

Simple + ES6 + no-dependency + supports boolean flags

const process = require( 'process' );

const argv = key => {
  // Return true if the key exists and a value is undefined
  if ( process.argv.includes( `--${ key }` ) ) return true;

  const value = process.argv.find( element => element.startsWith( `--${ key }=` ) );

  // Return null if the key does not exist and a value is undefined
  if ( !value ) return null;
  
  return value.replace( `--${ key }=` , '' );
}

Output:

  • If invoked with node app.js then argv('foo') will return null
  • If invoked with node app.js --foo then argv('foo') will return true
  • If invoked with node app.js --foo= then argv('foo') will return ''
  • If invoked with node app.js --foo=bar then argv('foo') will return 'bar'
6
  • Is if ( process.argv.includes( `--${ key }` ) ) not true for --foo=bar? I'm confused how it ever gets past that first conditional. Commented Apr 18, 2022 at 17:43
  • 1
    @temporary_user_name Ahh great question... includes is testing matching values in the argv array, not substrings in each argv entry. So the value must be an exact match: i.e. Testing argv with includes for the --foo element would not match --foo=bar, which would be separate value in the array. The next line, process.argv.find shows what the substring search looks like. Commented Apr 19, 2022 at 18:54
  • Oh that's so obvious now that you say it. I totally knew that and wasn't thinking. Thank you for the reminder. Commented Apr 19, 2022 at 20:06
  • 2
    @temporary_user_name All good... It's kind of good for readers to see the tradeoff with ES6 syntactic sugar and features... Short and concise does not always equal readable :P Commented Apr 19, 2022 at 20:40
  • 1
    @Andrew Odri the first comment that explains frist check includes( --${ key }` )` is wrong and very misleading. The comment should say: Returns true if the key exists and a value IS NOT defined Commented Mar 7 at 17:40
35

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 commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)

options now looks like this:

{
  src: [
    'one.js',
    'two.js'
  ],
  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.

usage

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

usage

Further Reading

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

0
34

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

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

console.log(args.foo)
console.log(args.fizz)

Example:

$ node test.js foo=bar fizz=buzz
bar
buzz

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

29

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);
console.log(argv._);

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

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

proj.js

for(var i=0;i<process.argv.length;i++){
  console.log(process.argv[i]);
}

Terminal:

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

Result:

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.

Explaination:

  1. The directory of node.exe in your machine (C:\Program Files\nodejs\node.exe)
  2. The directory of your project file (proj.js)
  3. Your first argument to node (arg1)
  4. Your second argument to node (arg2)
  5. Your third argument to node (arg3)

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

21

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' }

also,

we can change

    let [k, v = true] = arg.split('=')
    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' }
0
21

Parsing argument based on standard input ( --key=value )

const argv = (() => {
    const arguments = {};
    process.argv.slice(2).map( (element) => {
        const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
        if ( matches ){
            arguments[matches[1]] = matches[2]
                .replace(/^['"]/, '').replace(/['"]$/, '');
        }
    });
    return arguments;
})();

Command example

node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"

Result of argv: console.log(argv)

{
    name: "stackoverflow",
    id: "10",
    text: "Hello World"
}
0
20

Native Method

Nodejs team added util.parseArgs function in versions 18.3.0 and 16.17.0. So if you use these or higher versions of nodejs you can parse command line arguments with this native solution. parseArgs was experimental up to v18 and is stable from v20.

An example of usage from the documentation:

const {parseArgs} = require('node:util');

const args = process.argv;
const options = {
  foo: {
    type: 'boolean',
    short: 'f'
  },
  bar: {
    type: 'string'
  }
};
const {
  values,
  positionals
} = parseArgs({ args, options, allowPositionals: true });

console.log(values);
console.log(positionals);

Output sample:

$ node parseargs.js -f --bar b
[Object: null prototype] { foo: true, bar: 'b' }
[
  '/Users/mbelsky/.nvm/versions/node/v18.12.1/bin/node',
  '/Users/mbelsky/parseargs.js'
]
1
  • This feature holds promise, but it currently lacks a --help command, numeric arguments, and the ability to make arguments required or optional. Commented yesterday
16

In the node code require the built in process lib.

const {argv} = require('process')

Run the program with their arguments.

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

argv is the array that follows:

argv[0] = /usr/bin/node
argv[1] = /home/user/process-args.js
argv[2] = one
argv[3] = two=three
argv[4] = four
14

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

console.log(process.argv)

You will get array like

 ['node','args.js','arg1','arg2']
11
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'
0
9

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']);
0
8

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("=")})
    .map(function(y){args[y[0]]=y[1]});

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.

0
8

Passing arguments is easy, and receiving them is just a matter of reading the process.argv array Node makes accessible from everywhere, basically. But you're sure to want to read them as key/value pairs, so you'll need a piece to script to interpret it.

Joseph Merdrignac posted a beautiful one using reduce, but it relied on a key=value syntax instead of -k value and --key value. I rewrote it much uglier and longer to use that second standard, and I'll post it as an answer because it wouldn't fit as a commentary. But it does get the job done.

   const args = process.argv.slice(2).reduce((acc,arg,cur,arr)=>{
     if(arg.match(/^--/)){
       acc[arg.substring(2)] = true
       acc['_lastkey'] = arg.substring(2)
     } else
     if(arg.match(/^-[^-]/)){
       for(key of arg.substring(1).split('')){
         acc[key] = true
         acc['_lastkey'] = key
       }
     } else
       if(acc['_lastkey']){
         acc[acc['_lastkey']] = arg
         delete acc['_lastkey']
       } else
         acc[arg] = true
     if(cur==arr.length-1)
       delete acc['_lastkey']
     return acc
   },{})

With this code a command node script.js alpha beta -charlie delta --echo foxtrot would give you the following object


args = {
 "alpha":true,
 "beta":true,
 "c":true,
 "h":true,
 "a":true,
 "r":true
 "l":true,
 "i":true,
 "e":"delta",
 "echo":"foxtrot"
}
8

Solution using Set to solve the position issue if using simple args (without key+values).

For example both commands will return same result:

node server.js detail json
node server.js json detail
const args = new Set(process.argv.slice(2));

Then one can use args.has('detail') or args.has('json') without worrying about position.

1
  • like it a lot 🙏 just in case a nice addition might be to lowercase args e.g. new Set(process.argv.slice(2).map((a) => a.toLowerCase()));
    – Can Rau
    Commented Oct 6, 2023 at 17:18
6

Although Above answers are perfect, and someone has already suggested yargs, using the package is really easy. This is a nice package which makes passing arguments to command line really easy.

npm i yargs
const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);

Please visit https://yargs.js.org/ for more info.

1
  • Yargs doesn't affect how arguments are passed on command line, it only helps in reading them in code. Commented Nov 3, 2019 at 23:44
6

TypeScript solution with no libraries:

interface IParams {
  [key: string]: string
}

function parseCliParams(): IParams {
  const args: IParams = {};
  const rawArgs = process.argv.slice(2, process.argv.length);
  rawArgs.forEach((arg: string, index) => {
    // Long arguments with '--' flags:
    if (arg.slice(0, 2).includes('--')) {
      const longArgKey = arg.slice(2, arg.length);
      const longArgValue = rawArgs[index + 1]; // Next value, e.g.: --connection connection_name
      args[longArgKey] = longArgValue;
    }
    // Shot arguments with '-' flags:
    else if (arg.slice(0, 1).includes('-')) {
      const longArgKey = arg.slice(1, arg.length);
      const longArgValue = rawArgs[index + 1]; // Next value, e.g.: -c connection_name
      args[longArgKey] = longArgValue;
    }
  });
  return args;
}

const params = parseCliParams();
console.log('params: ', params);

Input: ts-node index.js -p param --parameter parameter

Output: { p: 'param ', parameter: 'parameter' }

5

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
  .slice(2)
  .map((val, i)=>{
    let object = {};
    let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
    let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
    if(!prop){
      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 }
console.log(args.host);//http://google.com
console.log(args.port);//8080
console.log(args.production);//true

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

1
  • 1
    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 }, {}) Commented Oct 13, 2017 at 12:23
5

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.

4

You can get command-line information from process.argv()

And I don't want to limit the problem to node.js. Instead, I want to turn it into how to parse the string as the argument.

console.log(ArgumentParser(`--debug --msg="Hello World" --title="Test" --desc=demo -open --level=5 --MyFloat=3.14`))

output

{
  "debug": true,
  "msg": "Hello World",
  "title": "Test",
  "desc": "demo",
  "open": true,
  "level": 5,
  "MyFloat": 3.14
}

code

Pure javascript, no dependencies needed

// 👇 Below is Test
(() => {
  window.onload = () => {
    const testArray = [
      `--debug --msg="Hello World" --title="Test" --desc=demo -open --level=5 --MyFloat=3.14`,
    ]
    for (const testData of testArray) {
      try {
        const obj = ArgumentParser(testData)
        console.log(obj)
      } catch (e) {
        console.error(e.message)
      }
    }
  }
})()

// 👇 Script
class ParserError extends Error {

}

function Cursor(str, pos) {
  this.str = str
  this.pos = pos
  this.MoveRight = (step = 1) => {
    this.pos += step
  }

  this.MoveToNextPara = () => {
    const curStr = this.str.substring(this.pos)
    const match = /^(?<all> *--?(?<name>[a-zA-Z_][a-zA-Z0-9_]*)(=(?<value>[^-]*))?)/g.exec(curStr) // https://regex101.com/r/k004Gv/2
    if (match) {
      let {groups: {all, name, value}} = match

      if (value !== undefined) {
        value = value.trim()
        if (value.slice(0, 1) === '"') { // string
          if (value.slice(-1) !== '"') {
            throw new ParserError(`Parsing error: '"' expected`)
          }
          value = value.slice(1, -1)
        } else { // number or string (without '"')
          value = isNaN(Number(value)) ? String(value) : Number(value)
        }
      }

      this.MoveRight(all.length)
      return [name, value ?? true] // If the value is undefined, then set it as ture.
    }
    throw new ParserError(`illegal format detected. ${curStr}`)
  }
}

function ArgumentParser(str) {
  const obj = {}
  const cursor = new Cursor(str, 0)
  while (1) {
    const [name, value] = cursor.MoveToNextPara()
    obj[name] = value
    if (cursor.pos === str.length) {
      return obj
    }
  }
}

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.