简体   繁体   中英

How to Pass a Command Line Argument in NodeJS?

I have a file structure, which I will enumerate for you in a moment. I have a web server, that initiates a command line process on a button press. I want to add in the option to run the server in a headless manner, using a command line argument. Is this the way I should be doing this? Here is my Project Structure.

/models
    /model1
    /model2
    /model3
/routes
    /index
    /test
    /users
    /credentials
    /adduser
/views
    /same as routes. Route 'test' has no layout.

in index, or '/', I have a function, which takes several parameters, and is initiated via clicking a button on the index page. We are then forwarded through 'test/run', and render the 'index' view. The process continues to run in the terminal. I will now post an example of the function.

    router.post('/run', ensureAuthenticated, function(req, res){
        return res.redirect('/test/running')
    });
    // Get Homepage
    router.get('/running', ensureAuthenticated, function(req, res){

        console.log(res.locals.user);
        // console.log(app.locals.user);


        const var1 = res.locals.user.username;
        const var2 = res.locals.user.username;
        const var3 = res.locals.user.username;
        const var4= res.locals.user.username;
        const deets = {
            var5,
            var6
        };

            res.render('index');

            dosomething(var1, var2, var3, var4, deets);
            setInterval(dosomething, 10 * 1000);
        })

    });

So what do you guys think? How would I be able to implement the passing of var1-6, through the command line? I would greatly appreciate any help from here.

I am running on Windows right now, but the target server is for Ubuntu systems.

In node.js you can pass CLI arguments using build in process variable

for examples

// test.js
var args = process.argv;
console.log(args[0]);  // it will give the node executable path
console.log(args[1]);   // it will give current file name
console.log(args[2]);   // cli arguments start index

now running the code

$ node test.js hello
/usr/bin/node
/home/blackdaemon/test.js
hello

If you like a pattern like "-arg" "value" try this:

var getArgs = function(){
    var arr = {};
    var last;
    process.argv.forEach((a, idx) => {
        if(idx > 1){
            if(last){
                arr[last] = a;
                last = undefined;
            }
            else if(!last && a.match(/-\w+/))
                last = a;
        }
    })
    return arr;
}

The result should be:

$ node index no valid command -ar3 dsds -arg1 323
{ '-ar3': 'dsds', '-arg1': '323' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM