How do I pass command line arguments to a Node.js program?

后端 未结 30 2649
梦如初夏
梦如初夏 2020-11-22 04:03

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:

相关标签:
30条回答
  • 2020-11-22 04:26

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

    process.argv.forEach((val, index) => {
      console.log(`${index}: ${val}`);
    })
    
    0 讨论(0)
  • 2020-11-22 04:27

    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' }
    
    0 讨论(0)
  • 2020-11-22 04:27

    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.

    0 讨论(0)
  • 2020-11-22 04:28

    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.

    0 讨论(0)
  • 2020-11-22 04:28

    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 讨论(0)
  • 2020-11-22 04:28

    The best way to pass command line arguments to a Node.js program is by using a Command Line Interface (CLI)

    There is a nifty npm module called nodejs-cli that you can use.

    If you want to create one with no dependencies I've got one on my Github if you wanna check it out, it's actually quite simple and easy to use, click here.

    0 讨论(0)
提交回复
热议问题