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

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

    proj.js

    for(var i=0;i

    Terminal:

    nodemon app.js "arg1" "arg2" "arg3"
    

    Result:

    0 'C:\\Program Files\\nodejs\\node.exe'
    1 'C:\\Users\\Nouman\\Desktop\\Node\\camer nodejs\\proj.js'
    2 'arg1' your first argument you passed.
    3 'arg2' your second argument you passed.
    4 'arg3' your third argument you passed.
    

    Explaination:

    0 : The directory of node.exe in your maching (C:\Program Files\nodejs\node.exe')

    1 : The directory of your project file. (proj.js)

    2 : Your first argument to node (arg1)

    3 : Your second argument to node (arg2)

    4 : Your third argument to node (arg3)

    your actual arguments start form 2nd index of argv array, that is process.argv[2].

提交回复
热议问题