All files / src/utils child-process.js

100% Statements 25/25
100% Branches 7/7
100% Functions 8/8
100% Lines 25/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52    1x   1x   1x 7x   7x 7x 7x   7x 2x     3x 1x     3x 1x     3x 1x     3x   3x 3x     3x 1x   2x           1x 2x 6x       1x  
'use strict';
 
const { ServerlessCommandError } = require('../common/errors');
 
let childProcesses = [];
 
const wrap = (childProcess, params = {}) => {
    childProcesses.push(childProcess);
 
    return new Promise((resolve, reject) => {
        let log = '';
        let errorLog = '';
 
        childProcess.stdout.on('data', data => {
            log += data.toString();
        });
 
        childProcess.stderr.on('data', data => {
            errorLog += data.toString();
        });
 
        if (params.stdout) {
            childProcess.stdout.pipe(params.stdout);
        }
 
        if (params.stderr) {
            childProcess.stderr.pipe(params.stderr);
        }
 
        childProcess.on('close', code => {
            // remove from sub-processes list
            childProcesses = childProcesses.filter(
                childProcessItem => childProcessItem !== childProcess
            );
 
            if (code !== 0) {
                reject(new ServerlessCommandError(code, log, errorLog));
            } else {
                resolve(log);
            }
        });
    });
};
 
const kill = () => {
    childProcesses.map(child => {
        child.kill();
    });
};
 
module.exports = { wrap, kill };