javascriptnode.jsdockerdockerode

How to get the output of the process using NodeJS dokerode library?


var Docker = require('dockerode');
var docker = new Docker({socketPath: '/var/run/docker.sock'});
var container = docker.getContainer('740aae30d312');
let params = {
    Cmd: ['sh','-c','ls -a $URL'],
    Env: ['URL=/home'],
    AttachStdout: true,
    AttachStderr: true,
  }
container.exec(params,(err, exec) => {
      err && console.error(err);
      exec.start({ hijack: true, stdin: false }, 
          function(err, stream) {
            docker.modem.demuxStream(stream, process.stdout, process.stderr);
          });
    },
  );

currently, this code shows the list of files in the container's home directory on the console. I need the same thing but in a variable


Solution

  • process.stdout being a stream, you can pipe to it directly instead of reading every chunk and using docker.modem.demuxStream(stream, process.stdout, process.stderr);

    stream.pipe(process.stdout);   
     var Docker = require('dockerode');
        var docker = new Docker({socketPath: '/var/run/docker.sock'});
        var container = docker.getContainer('471e865f0a96');
        container_output="";
        let params = {
            Cmd: ['sh','-c','ls -a $URL'],
            Env: ['URL=/home'],
            AttachStdout: true,
            AttachStderr: true,
          }
        container.exec(params,(err, exec) => {
              err && console.error(err);
              exec.start({ hijack: true, stdin: false }, 
                  function(err, stream) {
                    stream.setEncoding('utf8');
                  container_output=(stream.pipe(process.stdout));
                  console.log("Directory in container is" ,container_output)
                  });
            },
          );