Docker.Image.js

JavaScript source for A Docker module for Node.js, 61 lines. Raw file

const Security = require('Security')

const Docker =
{
    Daemon: require('./Docker.Daemon'),

    Image:
    {
        Add: ( imageName, dockerfilePath) =>
        {
            imageName = Security.String(imageName)
            dockerfilePath = Security.String(dockerfilePath)

            const command = [`build`, `-t ${imageName}`, `"${dockerfilePath}"`]
            Docker.Daemon.Execute( command )
        },

        Remove: ( imageName) =>
        {
            imageName = Security.String(imageName)

            if( Docker.Image.Exists(imageName) ) {
                const command = [`image`, `rm`, `${imageName}:latest`];
                const hasRemoved = Docker.Daemon.Execute( command )
                if (!hasRemoved) {
                    throw new Error("Unable to remove image")
                }
            }
        },

        Exists: ( imageName ) =>
        {
            imageName = Security.String(imageName)

            const command = [`images`, `-q`, imageName]
            const parsingCb = (input) => {

                if( input.trim() === '' ) {
                    return false;
                }

                const lines = input.trim().split('\n')
                const regExp = /^[a-f0-9A-F]+$/;
                const linesAreHashes = lines.map( line => regExp.test(line.trim()) )
                const allLinesAreHashes = linesAreHashes.reduce( (a,b) => a && b )

                if( allLinesAreHashes ) {
                    return true;
                }
                else {
                    throw new Error("Unexpected output from docker images: '" + input + "'")
                }
            };

            return Docker.Daemon.Execute(command, parsingCb)
        },

    }
}

module.exports = Docker.Image