使用参数生成顶部并使用 grep 进行解析

Spawning top with arguments and parsing with grep

我想使用一些参数生成 top 以获得当前的 cpu 负载和使用情况。
如果我在我的 ssh 会话中键入完整命令 top -bn1 | grep "Cpu(s)\|top -",我会得到完整且有效的响应。
但是如何使用 execFile 生成此命令的正确方法?

这就是我想要做的:

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

const execFile = util.promisify(childProcess.execFile)

async function getData() {
    // Not working
    const command = 'top -bn1 | grep "Cpu(s)\|top -"'
    const args = []
    
    // Also tried this
    const command = 'top'
    const args = ['-bn1 | grep "Cpu(s)\|top -"']
    
    const { stdout } = await execFile(command, args, { maxBuffer: 1000 * 1000 * 10 })
    console.log(stdout)
}
getData()

但是生成会失败并出现以下错误:

Error: spawn top -bn1 | grep "Cpu(s)|top -" ENOENT
    at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
    at onErrorNT (node:internal/child_process:480:16)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -2,
  code: 'ENOENT',
  syscall: 'spawn top -bn1 | grep "Cpu(s)|top -"',
  path: 'top -bn1 | grep "Cpu(s)|top -"',
  spawnargs: [],
  cmd: 'top -bn1 | grep "Cpu(s)|top -"',
  stdout: '',
  stderr: ''
}

我不知道您不能将多个命令(管道命令)合并到一个 execFile 中。但是您可以使用 shell 选项。

我现在的解决方案是使用 shell 选项:

const command = 'top -bn1 | grep "Cpu(s)\|top -"'
const args = []
const { stdout } = await execFile(command, args, { shell: true, maxBuffer: 1000 * 1000 * 10 })

或者,您可以将 stdout 通过管道传输到第二个 spawn(通过管道传输到 grep),但这对于我的简单任务来说有点太多了。