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

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

    Here's my 0-dep solution for named arguments:

    const args = process.argv
        .slice(2)
        .map(arg => arg.split('='))
        .reduce((args, [value, key]) => {
            args[value] = key;
            return args;
        }, {});
    
    console.log(args.foo)
    console.log(args.fizz)
    

    Example:

    $ node test.js foo=bar fizz=buzz
    bar
    buzz
    

    Note: Naturally this will fail when the argument contains a =. This is only for very simple usage.

提交回复
热议问题