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

后端 未结 30 2714
梦如初夏
梦如初夏 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:22

    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  -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  ] [--kaka] [--ooo] [--map]
      -c, --check     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
    

提交回复
热议问题