简体   繁体   English

将生成的stdout结果作为字符串变量存储在Node.js中

[英]Storing spawn stdout result as string variable in Node.js

I'm trying to return the output of this function into a variable to be used in another function, but the variable returns as undefined. 我正在尝试将此函数的输出返回到要在另一个函数中使用的变量,但是该变量返回的是未定义的。 What am I doing wrong? 我究竟做错了什么?

function run(cmd){
    var spawn = require('child_process').spawn;
    var command = spawn(cmd);
    var result = '';
      command.stdout.on('data', function(data) {
         result += data.toString();
      });
      command.on('close', function(code) {
         return result;
      });
}
var message = run("ls");
sendMessage(user, message);

Your run function is asynchronous (because spawn is). 您的run函数是异步的(因为spawn )。 The simplest method of passing its result would be to provide a callback function which is called when the results are in: 传递结果的最简单方法是提供一个回调函数,当结果位于时:

function run(cmd, cb) {
  var spawn = require('child_process').spawn;
  var command = spawn(cmd);
  var result = '';
  command.stdout.on('data', function(data) {
    result += data.toString();
  });
  command.on('close', function(code) {
    cb(result);
  });
}
run("ls", function(message) {
  sendMessage(user, message);
});

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

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