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

使用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命令还存在两个关键问题:

  1. 转义字符错误,"是HTML实体,需替换为普通双引号
  2. 修改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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:45:54