xvno / blog

个人博客, 不定期发布技术笔记和个人随笔.
0 stars 0 forks source link

Electron: Shell Scripts #142

Open xvno opened 3 years ago

xvno commented 3 years ago

Refs

xvno commented 3 years ago

child_process.spawn

const cp = require('child_process');
const process = cp.spawn(cmd, paramList);

proc.stdout.on("data", chunk => {
    log('data: ', chunk.toString());
});

proc.stderr.on('data', data => {
    stop(data);
});

proc.on('close', code => {
    log(`child process exited with code ${code}`);
    //TODO: update db.take
});

proc.on('exit', function (code, signal) {
    log(`proc: on-exit: code: ${code}, signal: ${signal}`);
    if (signal === 'SIGKILL') {
        let unlink = fs.unlinkSync(destFile);
        cb(null, {
            cxed: 0,
            op: 1,
            taskstate: CODE.CONVERT_PAUSED
        });
    } else {
        const stat = getStat(destFile);
        let size = 0;
        if (stat) {
            size = stat.size;
        }
        cb(null, {
            taskstate: CODE.CONVERT_SUCCESS,
            op: 1,
            total: size,
            taskendTS: Date.now()
        });
    }
});

function stop (data) {
    if (opt.suspend) {
        proc.kill('SIGKILL');
        cb(null, {
            taskstate: CODE.CONVERT_PAUSED,
            op: CODE.CONVERT_OP_PAUSE,
            total: 0,
            taskendTS: Date.now()
        });
        return;
    } else {
        console.log('Not suspended!');
    }
}
xvno commented 3 years ago

child_process.exec


function handleService (apiName, cmd, cmdArgs = [], {/*  args,  */sender, action, taskerid }) {
    log(apiName);
    const backStatus = {
        isSentBack: false
    };
    cmdArgs.unshift(cmd);
    log(cmdArgs.join(' '));
    exec(cmdArgs.join(' '), (err, stdout, stderr) => {
        if (err) {
            error(`${apiName}.error: `, err);
            return sendBack(
                backStatus,
                {
                    action,
                    sender,
                    code: CODE.STATE_ERROR,
                    message: MESSAGE.STATE_ERROR,
                    data: { detail: err.errno },
                    taskerid
                });

        }
        if (stderr) {
            log(`${apiName}.stderr: `, stderr);
            return sendBack(backStatus,
                {
                    action,
                    sender,
                    code: CODE.STATE_ERROR,
                    message: MESSAGE.STATE_ERROR,
                    data: { detail: stderr },
                    taskerid
                });
        }
        console.log(`stdout: ${stdout}`);
        log(`${apiName}.stdout: `, stdout);
        sendBack(backStatus, { action, sender, code: CODE.STATE_OK, message: MESSAGE.STATE_OK, data: { detail: stdout }, taskerid });
    });

}