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

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

    Passing arguments is easy, and receiving them is just a matter of reading the process.argv array Node makes accessible from everywhere, basically. But you're sure to want to read them as key/value pairs, so you'll need a piece to script to interpret it.

    Joseph Merdrignac posted a beautiful one using reduce, but it relied on a key=value syntax instead of -k value and --key value. I rewrote it much uglier and longer to use that second standard, and I'll post it as an answer because it wouldn't fit as a commentary. But it does get the job done.

       const args = process.argv.slice(2).reduce((acc,arg,cur,arr)=>{
         if(arg.match(/^--/)){
           acc[arg.substring(2)] = true
           acc['_lastkey'] = arg.substring(2)
         } else
         if(arg.match(/^-[^-]/)){
           for(key of arg.substring(1).split('')){
             acc[key] = true
             acc['_lastkey'] = key
           }
         } else
           if(acc['_lastkey']){
             acc[acc['_lastkey']] = arg
             delete acc['_lastkey']
           } else
             acc[arg] = true
         if(cur==arr.length-1)
           delete acc['_lastkey']
         return acc
       },{})
    

    With this code a command node script.js alpha beta -charlie delta --echo foxtrot would give you the following object

    
    args = {
     "alpha":true,
     "beta":true,
     "c":true,
     "h":true,
     "a":true,
     "r":true
     "l":true,
     "i":true,
     "e":"delta",
     "echo":"foxtrot"
    }
    

提交回复
热议问题