You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开启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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:57:00