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

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

    whithout librairies: using Array.prototype.reduce()

    const args = process.argv.slice(2).reduce((acc, arg) => {
    
        let [k, v = true] = arg.split('=')
        acc[k] = v
        return acc
    
    }, {})
    

    for this command node index.js count=2 print debug=false msg=hi

    console.log(args) // { count: '2', print: true, debug: 'false', msg: 'hi' }
    

    also,

    we can change

        let [k, v = true] = arg.split('=')
        acc[k] = v
    

    by (much longer)

        let [k, v] = arg.split('=')
        acc[k] = v === undefined ? true : /true|false/.test(v) ? v === 'true' : /[\d|\.]+/.test(v) ? Number(v) : v
    

    to auto parse Boolean & Number

    console.log(args) // { count: 2, print: true, debug: false, msg: 'hi' }
    

提交回复
热议问题