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

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

    Without libraries

    If you want to do this in vanilla JS/ES6 you can use the following solution

    worked only in NodeJS > 6

    const args = process.argv
      .slice(2)
      .map((val, i)=>{
        let object = {};
        let [regexForProp, regexForVal] = (() => [new RegExp('^(.+?)='), new RegExp('\=(.*)')] )();
        let [prop, value] = (() => [regexForProp.exec(val), regexForVal.exec(val)] )();
        if(!prop){
          object[val] = true;
          return object;
        } else {
          object[prop[1]] = value[1] ;
          return object
        }
      })
      .reduce((obj, item) => {
        let prop = Object.keys(item)[0];
        obj[prop] = item[prop];
        return obj;
      }, {});
    

    And this command

    node index.js host=http://google.com port=8080 production
    

    will produce the following result

    console.log(args);//{ host:'http://google.com',port:'8080',production:true }
    console.log(args.host);//http://google.com
    console.log(args.port);//8080
    console.log(args.production);//true
    

    p.s. Please correct the code in map and reduce function if you find more elegant solution, thanks ;)

提交回复
热议问题