dockerode icon indicating copy to clipboard operation
dockerode copied to clipboard

Getting one garbage character from container.exec()

Open jamesmurdza opened this issue 2 years ago • 10 comments

I've written two helper functions using Dockerode. The idea is to run a command synchronously and then return the results as a string.

It works well, except each chunk that is returned by stream.on('data') starts with a garbage character, like "X", "*", "!", etc. I can't figure out why.

This happens for multiple commands, such as "bash" and "cat".

Help is much appreciated!

My code below:

async function waitForStreamEnd(stream: NodeJS.ReadableStream): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    try {
      stream.on('end', async () => {
        resolve();
      });
    } catch (err) {
      reject(err);
    }
  });
}

async function runCommandInContainer(container: Docker.Container, command: string[]): Promise<string> {
  const exec = await container.exec({
    Cmd: command,
    AttachStdout: true,
    AttachStderr: true,
  });
  const stream = await exec.start({ hijack: true, stdin: true });
  let output = "";
  stream.on('data', (data) => {
    output += data;
  });
  await waitForStreamEnd(stream);
  return output;
}

jamesmurdza avatar Jun 10 '23 13:06 jamesmurdza

const readStream = (stream: stream.Duplex) => {
  let output: string = "";
  return new Promise<string>((resolve, reject) => {
    stream.on("data", (chunk: string) => {
      output += chunk;
    });

    stream.on("end", () => {
     // handle garbage
      resolve(output.trim().split("\n").map(processString).join("\n"));
    });
  });
  
  function processString(str: string): string {
    const out = Buffer.from(str, "binary");
    if (out.readUInt8(0) === 1) {
      return out.toString("utf8", 8);
    } else {
      return out.toString("utf8", 0);
    }
  }
};

May be this function can help you.

Akimyou avatar Jun 29 '23 07:06 Akimyou

Interesting, I will try this. Any explanation why this would work?

jamesmurdza avatar Jun 29 '23 11:06 jamesmurdza

add more comment i also has it issue but i guess it is docker' api problem, is not?

for example, exec with ping

image

i just console.log of exec result

Fhwang0926 avatar Jul 23 '23 14:07 Fhwang0926

@Fhwang0926 Were you able to figure out any solution?

jamesmurdza avatar Jul 30 '23 16:07 jamesmurdza