如何处理这个任务?
我需要从 Powershell.on 事件推送数据以将一些数据响应到客户端网页。但我不是一个好的程序员。如何做到这一点?:
router.all('/', (req, res, next) => {
var NetbiosName = req.query.hostname.split('.', 1);
var cmd = "New-ADComputer -Name " + NetbiosName[0] + " -SamAccountName " +
NetbiosName[0];
var gdata;
let ps = new PowerShell(cmd);
ps.on("error", err => {
console.error(err);
});
ps.on("output", data => {
//need to push this data to responce json
console.log(data);
});
ps.on("error-output", data => {
//need to push this data to responce json
console.error(data);
});
ps.on("end", code => {
});
//console.log(ps.send(['help',]));
res.status(200).json({
"hostname": req.query.hostname,
"userclass": req.query.userclass,
"host": NetbiosName[0],
"cmd": cmd,
"data": "Data from ps.on",
});
//console.log(util.inspect(req));
});
最佳答案
编写一个函数将数据发送回客户端。
function sendResponse(data) { res.status(200).json({ "hostname": req.query.hostname, "userclass": req.query.userclass, "host": NetbiosName[0], "cmd": cmd, "data": data }); }
从声明的事件输出和错误输出调用该函数
ps.on("output", data => { sendResponse(data); }); ps.on("error-output", data => { sendResponse(data); });
关于node.js - 如何使用 Express 将 powershell 命令结果推送到 NodeJs 中的 json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50014299/