开启ES6 Modules的Node.js中如何导入child_process执行Powershell脚本
适配ES Module模式的实现方案
在配置了"type": "module"的Node.js项目中,需要替换原CommonJS的require导入语法为ES模块的import语法,即可正常导入child_process模块实现Powershell脚本执行能力,适配后的两种实现代码如下:
适配exec实现方案
使用如下导入语句替换原有require写法即可:
// 加node:前缀是Node.js官方推荐的内置模块标识写法,也可以省略直接写child_process import { exec } from 'node:child_process'; exec('command here', {'shell':'powershell.exe'}, (error, stdout, stderr)=> { // 自行处理stdout返回内容 })
适配spawn实现方案
导入语句调整如下:
import { spawn } from 'node:child_process'; const child = spawn("powershell.exe",["c:\\temp\\helloworld.ps1"]); child.stdout.on("data",function(data){ console.log("Powershell Data: " + data); }); child.stderr.on("data",function(data){ console.log("Powershell Errors: " + data); }); child.on("exit",function(){ console.log("Powershell Script finished"); }); child.stdin.end(); //结束输入
注意事项
需要确保当前运行的Node.js版本不低于14.13.0,该版本开始官方稳定支持ES模块模式下导入内置核心模块。
内容的提问来源于stack exchange,提问作者Baul
相关产品推荐
相关产品推荐

