4

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.

2 Answers 2

7

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 
Sign up to request clarification or add additional context in comments.

2 Comments

That sounds perfect! Thank you very much, I will give it a try now :D
better use process.argv.splice(2) to extract only an array of cli arguments. thanks
0

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' } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.