node.jsdockerdockerode

How can i capture stdout from dockerode when using promises?


I am trying to run a docker container using dockerode following the examples here.

The issue I am having is that the output of the container prints to stdout, but I am trying to capture it and store it in a variable while using promises if possible.

My code is:

const Docker = require('dockerode');

const docker = new Docker();

docker
    .run(
        'wappalyzer/cli',
        ['https://www.wappalyzer.com'],
        [process.stdout, process.stderr],
        { Tty: false }
    )
    .then((data) => {
        let output = data[0];
        let container = data[1];
        console.log(typeof output);
        console.log(output);
        return container.remove();
    })
    .catch((error) => console.log(error));

Solution

  • For docker.run(), The [ process.stdout, process.stderr ] streams are where the underlying stdio data is piped to.

    Change these arguments to writable streams you control. You can use something like a memory stream, a file or implement a stream yourself.

    const Docker = require('dockerode')
    const streams = require('memory-streams')
    
    const docker = new Docker()
    const stdout = new streams.WritableStream()
    const stderr = new streams.WritableStream()
    
    docker.run(
        'debian:10',
        ['sh', '-c', 'echo test; echo testerr >/dev/stderr; echo test3'],
        [stdout, stderr],
        { Tty: false }
      )
      .then(([ res, container ]) => {
          console.log(res)
          console.log('stdout: %j', stdout.toString())
          console.log('stderr: %j', stderr.toString())
          return container.remove()
      })
      .catch((error) => console.log(error))