【问题标题】:how to use grep command programmatically in node.js如何在 node.js 中以编程方式使用 grep 命令
【发布时间】:2017-12-11 08:31:06
【问题描述】:

我正在尝试仅显示 vmRSS 属性。当我运行命令命令时

cat ./Status

我得到了很多属性及其对应的值。我想要做的是以编程方式仅显示 vmRSS 。我可以在控制台中这样做:

cat ./status | grep VmR

但我怎样才能以编程方式做到这一点。

我的尝试

const ls2 = spawn('cat', ['/proc/' + process.pid + '/status']);

【问题讨论】:

标签: javascript node.js linux grep


【解决方案1】:

由于 child_process spawn 在子进程中启动 shell,我认为您最好在当前 shell 中执行此操作,而使用 child_process exec() 命令.

这是一个例子(感谢@Inian):

const { exec } = require('child_process');

exec('grep VmR /proc/' + process.pid + '/status', (err, stdout) => {
  if (err) return console.log(err)
  console.log(stdout)  // VmRSS:     13408 kB
})

否则,如果您不想生成 shell 来获取该信息,则可以使用 fs 来读取文件,如下所示:

const fs = require('fs');

let process_status = '/proc/' + process.pid + '/status';

fs.readFile(process_status, { encoding: 'utf8' }, (err, buf) => {
  if (err) return console.log(err)

  let lines = buf.split('\n')  // each line in an array
  let line = lines.filter(line => /VmRSS/.test(line))  // find interesting line
  let VmR = line[0].replace(/\t/g, '')  // clean output removing tabulation

  console.log(VmR)  // VmRSS:   13208 kB

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 2010-12-16
    • 2013-08-14
    • 2015-09-10
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多