使用参数生成top并使用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管道到第二个衍生(管道到grep),但对于我的简单任务来说,这有点太多了。

最新更新