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

如何使用Node.js execFile执行带grep管道的top命令获取CPU使用率

错误原因

execFile 底层直接调用系统spawn执行二进制程序,不会创建shell环境,因此所有shell专属语法(管道|、字符串引号、逻辑运算符等)都无法被识别。你之前的两种写法分别踩了两个坑:

  • 第一种把带管道的完整命令当成了可执行文件路径,系统中不存在同名文件,直接抛出ENOENT错误
  • 第二种把管道、grep相关内容当成参数传给top程序,top本身不识别这类参数,同样无法正常运行
解决方案

方案1:通过execFile调用shell执行整条命令

如果你需要保留原命令的管道写法,可以显式调用shell程序来执行整条命令,示例代码如下:

import childProcess from 'child_process'
import util from 'util'

const execFile = util.promisify(childProcess.execFile)

async function getData() {
    // 执行shell,传入-c参数指定要运行的完整命令
    const command = 'bash'
    const args = ['-c', 'top -bn1 | grep "Cpu(s)\\|top -"']
    
    const { stdout } = await execFile(command, args, { maxBuffer: 10 * 1024 * 1024 })
    console.log(stdout)
}
getData()

注意要对命令字符串里的反斜杠做二次转义,避免JavaScript字符串解析时把转义符吃掉。

方案2(更推荐):Node.js层处理输出,不需要grep

直接执行top命令拿到完整输出后,在JavaScript代码中做字符串匹配,不需要依赖shell和grep,兼容性和安全性更高,也避免了shell语法的转义问题:

import childProcess from 'child_process'
import util from 'util'

const execFile = util.promisify(childProcess.execFile)

async function getData() {
    const command = 'top'
    const args = ['-bn1']
    
    const { stdout } = await execFile(command, args, { maxBuffer: 10 * 1024 * 1024 })
    // 筛选匹配的行
    const result = stdout.split('\n').filter(line => line.includes('Cpu(s)') || line.includes('top -'))
    console.log(result.join('\n'))
}
getData()

内容的提问来源于stack exchange,提问作者borsTiHD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:27:04