在Meteor/Node中确定从服务器返回的输出是标准错误还是标准输出

Determine if returned output from server is stderr or stdout on client in Meteor/Node?

本文关键字:输出 标准 错误 标准输出 返回 服务器 Node Meteor      更新时间:2023-09-26

我运行用户给出的exec命令并将其输出返回给客户端。当我返回结果时,一切都很好,但是我需要基于标准输出和标准错误运行两个不同的if场景。如何确定返回的输出是标准输出还是标准错误?在这种情况下,它总是像stdout一样运行。

*我需要直接解决方案,希望避免使用集合。注意,这只是示例代码。

服务器:

// load future from fibers
var Future = Meteor.npmRequire("fibers/future");
// load exec
var exec = Meteor.npmRequire("child_process").exec;
Meteor.methods({
  'command' : function(line) {
    // this method call won't return immediately, it will wait for the
    // asynchronous code to finish, call unblock to allow this client
    this.unblock();
    var future = new Future();
    exec(line, function(error, stdout, stderr) {
      if(stdout){
        console.log(stdout);
        future.return(stdout);
      } else {
        console.log(stderr);
        future.return(stderr);
      }
    });
    return future.wait();
  }
});

客户:

var line = inputdl.value;
Meteor.call('command', line, function(error, stdout, stderr) {
  if(stdout){
    console.log(stdout);
  } else {
    alert('Not valid command: ' + stderr); 
  }
});

可以返回一个同时包含stdout和stderr的对象:

Meteor.methods({
  'command' : function(line) {
    this.unblock();
    var future = new Future();
    exec(line, function(error, stdout, stderr) {
       future.return({stdout: stdout, stderr: stderr});
    });
    return future.wait();
  }
});

和客户端:

Meteor.call('command', line, function(error, result) {
  if(result.stdout){
    console.log(result.stdout);
  } else {
    alert('Not valid command: ' + result.stderr); 
  }
});