我正在使用dockerode
庫,我想創建一個容器,執行一個(單個)命令並返回(單獨)標準輸出和標準錯誤該命令。從Node.js中的碼頭容器獲取stdout和stderr流
到目前爲止,我能夠得到標準輸出,但我沒有運氣標準錯誤。我發現很多方法在Github的問題,但沒有一個工作。
的代碼我已經是(我使用的承諾和協同程序,以避免回調):
const Promise = require('bluebird');
const coroutine = Promise.coroutine;
const Docker = require('dockerode');
const docker = coroutine.promisifyAll(new Docker());
const foo = coroutine(function*(){
let container = Promise.promisifyAll(yield docker.createContainerAsync(/*...*/));
yield container.startAsync(/*...*/);
const execOpts = {Cmd: /*...*/, AttachStdout: true, AttachStderr: true, Tty: true};
const exec = Promise.promisifyAll(yield container.execAsync(execOpts));
const stream = yield exec.startAsync();
let data = [];
stream.on('data', chunk => {
data.push(chunk);
});
stream.on('end',() => {
stdoutData = Buffer.concat(data).toString()
});
let executionData = yield exec.inspectAsync();
while (executionData.Running) { executionData = yield exec.inspectAsync(); }
return {
stdout: stdoutData,
stderr:
}
});
注意:在dockerode's npm documentation有這個例子中實現我想要的東西,但我無法找出什麼全局對象process
,以及如何使用它在我的代碼:
//tty:true
docker.createContainer({ /*...*/ Tty: true /*...*/ }, function(err, container) {
/* ... */
container.attach({stream: true, stdout: true, stderr: true}, function (err, stream) {
stream.pipe(process.stdout);
});
/* ... */
}
//tty:false
docker.createContainer({ /*...*/ Tty: false /*...*/ }, function(err, container) {
/* ... */
container.attach({stream: true, stdout: true, stderr: true}, function (err, stream) {
//dockerode may demultiplex attach streams for you :)
container.modem.demuxStream(stream, process.stdout, process.stderr);
});
/* ... */
}
docker.createImage({fromImage: 'ubuntu'}, function (err, stream) {
stream.pipe(process.stdout);
});