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

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

    You can parse all arguments and check if they exist.

    file: parse-cli-arguments.js:

    module.exports = function(requiredArguments){
        var arguments = {};
    
        for (var index = 0; index < process.argv.length; index++) {
            var re = new RegExp('--([A-Za-z0-9_]+)=([A/-Za-z0-9_]+)'),
                matches = re.exec(process.argv[index]);
    
            if(matches !== null) {
                arguments[matches[1]] = matches[2];
            }
        }
    
        for (var index = 0; index < requiredArguments.length; index++) {
            if (arguments[requiredArguments[index]] === undefined) {
                throw(requiredArguments[index] + ' not defined. Please add the argument with --' + requiredArguments[index]);
            }
        }
    
        return arguments;
    }
    

    Than just do:

    var arguments = require('./parse-cli-arguments')(['foo', 'bar', 'xpto']);
    

提交回复
热议问题