Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
TylerDurden Avatar asked Nov 04 '25 17:11

TylerDurden


1 Answers

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
like image 111
tbhaxor Avatar answered Nov 07 '25 10:11

tbhaxor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!