【问题标题】:NodeJS capture/read output of process.stdoutNodeJS 捕获/读取 process.stdout 的输出
【发布时间】:2021-07-22 08:49:26
【问题描述】:

我正在尝试处理使用 process.stdout / process.stdin 将命令结果打印到终端的特定函数的输出。更具体地说,这个 Kubernetes 函数 https://github.com/kubernetes-client/javascript/blob/master/src/exec.ts 具有这种用法:

const exec = new k8s.Exec(kc);
exec.exec('default', 'nginx-4217019353-9gl4s', 'nginx', command,
    process.stdout, process.stderr, process.stdin,
    true /* tty */,
    (status) => {
        console.log('Exited with status:');
        console.log(JSON.stringify(status, null, 2));
    });

虽然上面的函数可能会向终端打印类似的内容:

Everything is up.
Time running: 5min 23sec.

Exited with status:
{
  "metadata": {},
  "status": "Success"
} 

我的目标是捕捉

Everything is up.
Time running: 5min 23sec.

在一个变量中,以便我可以进一步处理它。

【问题讨论】:

    标签: node.js kubernetes stdout stdin


    【解决方案1】:

    创建自己的流对象而不是使用来自进程/控制台的流对象效果很好。

    var Stream = require('stream');
        
    var ws = new Stream;
    ws.writable = true;
    ws.str = "";
    ws.str = 0;
    
    ws.string = function(){
      return ws.str;
    }
    
    ws.clearStr = function(){
      ws.str = "";
    }
    
    ws.write = function(buf) {
      ws.str += buf.toString();
      ws.bytes += buf.length;
    }
    
    ws.end = function(buf) {
       if(arguments.length) ws.write(buf);
       ws.writable = false;
    }
    
    async function kubeExec(ns, pod, container, cmd){
      ws.clearStr();
      ret = new Promise((resolve,reject) =>{
        execV1Api.exec(ns,pod,container,cmd, ws, process.stderr , process.stdin,true /* tty */,
          async function(ret){
              if(ret.status == "Success"){
                resolve(ws.str);
              } else {
                console.log(JSON.stringify(status, null, 2));
              }
          });
      });
    
      return ret.then( (str) => { return str;} );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2014-04-19
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多