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

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

    Most of the people have given good answers. I would also like to contribute something here. I am providing the answer using lodash library to iterate through all command line arguments we pass while starting the app:

    // Lodash library
    const _ = require('lodash');
    
    // Function that goes through each CommandLine Arguments and prints it to the console.
    const runApp = () => {
        _.map(process.argv, (arg) => {
            console.log(arg);
        });
    };
    
    // Calling the function.
    runApp();
    

    To run above code just run following commands:

    npm install
    node index.js xyz abc 123 456
    

    The result will be:

    xyz 
    abc 
    123
    456
    

提交回复
热议问题