node.js执行shell命令进行服务器重启

nodejs功能强大且多样,不只是可以实现 服务器端 与 客户端 的实时通讯,另一个功能是用来执行shell命令

1、首先,引入子进程模块
var process = require('child_process');
2、然后,调用该模块暴露出来的方法exec
process.exec('shutdown -h now',function (error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
});
回调函数非必须!

3、具体案例 
var express = require('express');
var app = express();
var process = require('child_process');

app.get('/restart/ccss', function (req, res) {
res.send('OK');
process.exec('shutdown -r now',function (error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
}
});
})

var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
})
 4、Linux下解决“shutdown: command not found"问题
1、首先查看shutdown命令的所在位置,即路径,输入语句whereis shutdown,找到其位置。

2、然后查看环境变量配置文件.bash_profile,在文件的最后加入PATH=$PATH:xxxx。(如果shutdown在/sbin/shutdown,那么xxxx就是/sbin)

3、之后用source ~/.bash_profile执行一下文件。这样就可以正常使用shutdown了。

原文地址:https://www.cnblogs.com/zzsdream/p/11972609.html