简体   繁体   English

(Node.js)如何将stdout.pipe存储到变量中?

[英](Node.js) How to store stdout.pipe into a variable?

I want to get free -m (linux shell command) and store its result into a variable by using source code below: 我想获得免费的-m(Linux shell命令),并通过使用以下源代码将其结果存储到变量中:

 var spawn = require('child_process').spawn,
     command  = spawn('free', ['-m']);
 command.stdout.pipe(process.stdout);

Is there any way to store process.stdout in a variable, please me some suggestions 有什么方法可以将process.stdout存储在变量中,请给我一些建议

This is fairly simple with child_process.exec : 这对于child_process.exec非常简单:

var child = require("child_process");
var freeOut;
child.exec("free", ["-m"], function (error, stdout, stderr) {
  if (error) {
    console.error(error, stderr);
    return;
  }
  //stdout and stderr are available here
  freeOut = stdout;
  process.stdout.write(stdout);
});
//Note. Do NOT use freeOut here. exec is async. Can only use in the callback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM