[英]How to Pass a Command Line Argument in NodeJS?
我有一个文件结构,我稍后将为您列举。 我有一个Web服务器,它在按下按钮时启动命令行进程。 我想添加使用命令行参数以无头方式运行服务器的选项。 这是我应该这样做的方式吗? 这是我的项目结构。
/models
/model1
/model2
/model3
/routes
/index
/test
/users
/credentials
/adduser
/views
/same as routes. Route 'test' has no layout.
在索引或'/'中,我有一个函数,它接受几个参数,并通过单击索引页面上的按钮启动。 然后我们通过'test / run'转发,并呈现'index'视图。 该过程继续在终端中运行。 我现在将发布一个函数示例。
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);
})
});
那你觉得怎么样? 我怎样才能通过命令行实现var1-6的传递? 我非常感谢这里的任何帮助。
我现在正在Windows上运行,但目标服务器是用于Ubuntu系统的。
在node.js中,您可以使用build in process
变量传递CLI参数
举些例子
// 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
现在运行代码
$ node test.js hello
/usr/bin/node
/home/blackdaemon/test.js
hello
如果您喜欢“-arg”“value”这样的模式,请尝试以下方法:
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;
}
结果应该是:
$ node index no valid command -ar3 dsds -arg1 323
{ '-ar3': 'dsds', '-arg1': '323' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.