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

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

    Parsing argument based on standard input ( --key=value )

    const argv = (() => {
        const arguments = {};
        process.argv.slice(2).map( (element) => {
            const matches = element.match( '--([a-zA-Z0-9]+)=(.*)');
            if ( matches ){
                arguments[matches[1]] = matches[2]
                    .replace(/^['"]/, '').replace(/['"]$/, '');
            }
        });
        return arguments;
    })();
    

    Command example

    node app.js --name=stackoverflow --id=10 another-argument --text="Hello World"
    

    Result of argv: console.log(argv)

    {
        name: "stackoverflow",
        id: "10",
        text: "Hello World"
    }
    

提交回复
热议问题