
var spawn = require('child_process').spawn;
var iconv = require("iconv-lite");

Buffer.prototype.GBKDecode = function () {
    return iconv.decode(this, 'cp936')
}

function shell({ cmd, args, opts, timeout = 0 }) {
    var encoding = 'buffer';

    return new Promise((resolve, reject) => {
        if (opts == undefined) opts = {};

        Object.assign(opts, { timeout, encoding })

        let c = spawn(cmd, args, opts);
        let error = '';
        let stdout = ''
        c.stdout.on('data', (data) => {
            data = data.GBKDecode()
            stdout += data;
        });

        c.stderr.on('data', (data) => {
            data = data.GBKDecode()
            error += data;
        });

        c.on('close', (code) => {
            resolve({ error, stdout });
        });

    })

};

module.exports = {
    shell
}