javascript - 在节点 js 中使用回调函数执行 powershell 脚本
问题描述
我编写了一个节点 JS 脚本,它应该使用 PowerShell 命令行执行。然后将 PowerShell 响应返回给 angularjs。PowerShell 命令的执行时间超过 5 分钟。所以节点正在向 angularjs 发送一个空响应。为此,我尝试了回调函数。但我得到了同样空洞的回应。请帮我解决这个问题。
这是在节点 js 中使用回调函数执行 powershell 的代码
let ps = new shell({
executionPolicy: 'Bypass',
noProfile: true
});
function getData(callback){
ps.addCommand('C:/Users/sowmi096/Desktop/Code/jobid.ps1',a)
ps.invoke()
.then(output => {
return callback(null,output);
})
.catch(err => {
return callback(null,err);
ps.dispose();
});
}
getData(function onGetData(err,data){
if(err)
res.send(err);
res.send(data);
});
解决方案
tl;博士:
要让您的 PowerShell 命令完成执行,您必须调用ps.dispose()
.
看起来您正在使用node-powershell
npm 包并尝试调整其示例代码。
不幸的是,在撰写本文时,此示例代码存在缺陷,因为它ps.dispose()
在成功案例中缺少对代码的调用,这意味着 PowerShell 命令永远不会退出。
这是一个工作示例(假设软件包已安装npm install node-powershell
):
const shell = require('node-powershell')
let ps = new shell({
executionPolicy: 'Bypass',
noProfile: true
});
// You can pack everything into the 1st argument or pass arguments as
// parameter-name-value objects; note the need to use null for [switch] parameters.
ps.addCommand("write-verbose", [ { verbose: null }, { message: 'hello, world'} ])
// IMPORTANT: ps.dispose() MUST be called for execution to finish.
ps.invoke()
.then(output => {
console.log(output)
ps.dispose() // This was missing from your code.
})
.catch(err => {
console.log(err)
ps.dispose()
});
推荐阅读
- regex - 正则表达式查找不连续的重复单词(即在字符串中出现多次)
- reactjs - 如何在反应中从类名中检索文本
- c++ - 我需要了解这个 cpp 代码背后的逻辑
- javascript - WP enqueue 脚本顺序和本地化错误,需要挂钩吗?
- azure - 天蓝色的前门 - 为什么故障转移不起作用
- javascript - 如何在 Cypress 中编写场景大纲特征的步骤定义文件
- javascript - 将循环结构转换为 JSON 时出错...采取 2
- python - 有没有办法在 matplotlib 中使轴标签变为粗体和斜体
- zalenium - Zalenium 是否有任何公开的 API 来查看实时执行
- c# - 如何获取日期和时间字符串的中间字符?