Docker from Node
Wouldn’t it be awesome if you could use the power of Docker
and docker containers together with the flexibility of NodeJs
? Well it turns out you can and it’s not very difficult.
Node
has a module called spawn
with which you can spawn any process you want, which includes Docker
(as long as it is installed on your system).
Code of the Day
const {spawn} = require('child_process');
const readline = require('readline');
async function buildDocker() {
await runCommand('docker build -t exector-test:test .');
}
async function runDocker() {
await runCommand('docker run exector-test:test');
}
function runCommand(fullCommand) {
return new Promise((resolve, reject) => {
const commandParts = fullCommand.split(' ');
const command = commandParts[0]
const compileProcess = spawn(
command,
commandParts.slice(1),
{
shell: true
});
compileProcess.on('close', (code) => {
if(code === 0) {
resolve();
} else {
reject(`Process finished with exit code ${code}`)
}
});
connectOutputs(compileProcess, console.log, console.error);
})
}
function connectOutputs(childProcess, stdout, stderr) {
childProcess.stdout && createInterface(childProcess.stdout, stdout);
childProcess.stderr && createInterface(childProcess.stderr, stderr);
}
function createInterface(input, output) {
const rlInterface = readline.createInterface ( {
input: input
});
rlInterface.on ( 'line', output);
}
The whole connectOutputs
story is to connect the output from the spawned process into the terminal output.