I am trying to process the output of a specific function that uses process.stdout / process.stdin to print the commands results to the terminal. To be more specific, this Kubernetes function https://github.com/kubernetes-client/javascript/blob/master/src/exec.ts with this usage:
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));
});
While the function above may print something like that to the terminal:
Everything is up.
Time running: 5min 23sec.
Exited with status:
{
"metadata": {},
"status": "Success"
}
My goal is to capture
Everything is up.
Time running: 5min 23sec.
in a variable so that I can process it further.
2
Answers
Creating an own stream object instead of using the one from process / console works good.
An year later, and I have this exact need, and still no viable solution to use the exec API to capture the
Writable
stream. The problem with this API is that theWritable
is also async, so you’ll need to wait for it to yield data. But you can’t wait while calling theexec.exec
, because the command won’t be executed, and so you either end up with no data, or infinite loop.The best solution I can come up with is to use another process to run the
kubectl exec
directly (e.g. if you’re writing tests with cypress, usecy.exec()
and then wait for the response). Below is a working solution for me:It’s worth nothing that you can combine this with other k8s client API, such as the
listNamespacedPod
to get the actual podName above at runtime, like this: