使用child_process执行PowerShell命令时遇exec is not a function错误
解决
exec is not a function错误及PowerShell命令问题 错误原因分析
你遇到的exec is not a function核心问题是模块导入方式不匹配:代码混合使用了CommonJS的require和ES模块(ESM)的export default,在ESM环境下,require无法正确加载child_process模块的导出,导致解构出的exec为undefined。
此外,你的PowerShell命令还存在两个关键问题:
- 转义字符错误,
"是HTML实体,需替换为普通双引号 - 修改HKLM注册表项需要管理员权限,普通用户运行会因权限不足报错
分步解决方案
1. 修正模块导入(ESM环境)
如果项目是ES模块(package.json中设置了"type": "module"),改用import语法导入:
import { exec } from 'child_process'; export default function boostFps() { // 修正转义并添加提权逻辑的PowerShell命令 const command = 'powershell -Command "& {Start-Process powershell -ArgumentList \'-Command Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile\" -Name SystemResponsiveness -Value 0\' -Verb RunAs}"'; exec(command, (err, stdout, stderr) => { if (err) { console.error('执行出错:', err); return; } console.log('执行输出:', stdout); if (stderr) console.error('错误输出:', stderr); }); }
2. 转义与提权逻辑修正
- 替换所有
"为双引号",避免命令解析失败 - 添加
Start-Process powershell -Verb RunAs,以管理员身份启动PowerShell执行注册表修改,解决权限不足问题
3. 备用方案(CommonJS环境)
如果项目是CommonJS环境(未设置"type": "module"),移除export default,改用module.exports:
const { exec } = require('child_process'); function boostFps() { const command = 'powershell -Command "& {Start-Process powershell -ArgumentList \'-Command Set-ItemProperty -Path \"HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Multimedia\\SystemProfile\" -Name SystemResponsiveness -Value 0\' -Verb RunAs}"'; exec(command, (err, stdout, stderr) => { if (err) { console.error('执行出错:', err); return; } console.log('执行输出:', stdout); if (stderr) console.error('错误输出:', stderr); }); } module.exports = boostFps;
额外说明
- 执行时系统会弹出UAC权限请求窗口,需用户手动确认
- 将
SystemResponsiveness设为0会降低后台进程优先级,提升前台应用帧率,但可能影响后台任务性能,建议按需调整
内容的提问来源于stack exchange,提问作者loan heron
相关产品推荐
相关产品推荐

