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

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

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

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

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

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

    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.

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

    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.

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

    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' ]
    
    0 讨论(0)
提交回复
热议问题