1

I am using the @kubernetes/client-node library.
My end goal is to execute commands (say "ls") and get the output for further processing. The .exec() method requires providing two Writeable streams (for the WebSocket to write the output to), and one Readable stream (for pushing our commands to).

The code I have looks something like this:

    const outputStream = new Stream.Writable();
    const commandStream = new Stream.Readable();

    const podExec = await exec.exec(
      "myNamespace",
      "myPod",
      "myContainer",
      ["/bin/sh", "-c"],
      outputStream,
      outputStream,
      commandStream,
      true
    );

    commandStream.push("ls -l\n");
    // get the data from Writable stream here
    outputStream.destroy();
    commandStream.destroy();
    podExec.close();

I am pretty new to JS and am having trouble getting the output from the Writable stream since it doesn't allow direct reading. Creating a Writable stream to a file and then reading from it seems unnecessarily overcomplicated.

I would like to write the output as a string to a variable.

Has anyone encountered the same task before, and if so, what can you suggest to get the command output?
I would appreciate any help on this matter!

Abraham
  • 185
  • 1
  • 10

1 Answers1

0

You can write your own Writable backed by a buffer. You can also reuse existing one. In your example you have @kubernetes/client-node. Looking at the kubernetes client source code I have found they are using @types/stream-buffers (https://github.com/samcday/node-stream-buffer#readme) in tests (for example in javascript/src/portforward_test.ts).

One more thing that is important - the result from exec.exec is a Promise to WebSocket, but to be sure the command finished you need to wait for the status (available in the status callback).

Here is my example:

var streamBuffers = require('stream-buffers');
const osStream = new WritableStreamBuffer();
const errStream = new WritableStreamBuffer();
const isStream = new ReadableStreamBuffer();

await exec.exec(
  "namespaceName", 
  "podName", 
  "containerName", 
  "ls -l", 
  outStream, 
  errStream, 
  isStream, 
  true,
  (status: k8s.V1Status)) => {
    console.log(outStream.getContentsAsString());
  });
bartosz.r
  • 454
  • 4
  • 10