Docker.Daemon.js
JavaScript source for A Docker module for Node.js, 71 lines. Raw file
const Security = require('Security');
const { spawnSync } = require('child_process')
const Docker =
{
Daemon:
{
Execute: (args, parsingCb) =>
{
args = Security.Array(Security.String)(args)
Security.OptionalCallback(parsingCb)
Docker.Daemon.Check()
const { stdout, stderr, status } = spawnSync("docker", args, {shell: true})
const stderrStr = stderr.toString()
const stdoutStr = stdout.toString()
if (status !== 0) {
throw new Error(`An error has occurred whilst running docker command.\nSTDERR: "${stderrStr}"\n with arguments:\n${JSON.stringify(args)}`)
}
else if( parsingCb ) {
return parsingCb(stdoutStr)
}
else {
return stdoutStr
}
},
/**
* Checks that the Docker daemon is running
*
* @throws Error if the daemon is not running
*/
Check: () =>
{
const { stdout, stderr, status } = spawnSync("docker", ['-v'], {shell: true})
const stderrStr = stderr.toString()
const stdoutStr = stdout.toString()
if (status !== 0) {
throw new Error(`An error has occurred whilst running docker command \n${stderrStr}'\n`)
}
else {
let inputSplitByLines = Docker.Daemon.SplitOutput( stdoutStr )
let filteredLines = inputSplitByLines.filter( line => line.includes("version") )
if ( filteredLines.length===0 ) {
throw new Error("Docker is not installed on this machine")
}
}
},
SplitOutput: (outputProvided) =>
{
outputProvided = Security.String(outputProvided)
const inputSplitByLines = outputProvided.split("\n")
const inputCleaned = inputSplitByLines.filter( line => line!=="" )
if (inputCleaned.length===0) {
throw new Error("This command returned empty result")
}
return inputCleaned;
}
}
}
module.exports = Docker.Daemon