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

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

    as stated in the node docs The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched.

    For example, assuming the following script for process-args.js:

    // print process.argv
    process.argv.forEach((val, index) => {
       console.log(`${index}: ${val}`);
    });
    

    Launching the Node.js process as:

     $ node process-args.js one two=three four
    

    Would generate the output:

    0: /usr/local/bin/node
    1: /Users/mjr/work/node/process-args.js
    2: one
    3: two=three
    4: four
    

提交回复
热议问题