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

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

    No Libs with Flags Formatted into a Simple Object

    function getArgs () {
        const args = {};
        process.argv
            .slice(2, process.argv.length)
            .forEach( arg => {
            // long arg
            if (arg.slice(0,2) === '--') {
                const longArg = arg.split('=');
                const longArgFlag = longArg[0].slice(2,longArg[0].length);
                const longArgValue = longArg.length > 1 ? longArg[1] : true;
                args[longArgFlag] = longArgValue;
            }
            // flags
            else if (arg[0] === '-') {
                const flags = arg.slice(1,arg.length).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'
    }
    

提交回复
热议问题