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

后端 未结 30 2659
梦如初夏
梦如初夏 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: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' }
    

提交回复
热议问题