Node rar压缩/解压文件

暂时未发现node有好用的rar解压/压缩库,所以就自己搜索了一下,简单写了一个,并做了个简单的封装。

rar文件的压缩/解压是通过命令行来完成的,所以就需要node 的child_process库,这个npm i xxx就可以了。

大概了解了下rar的语法,这个在WinRAR的安装文件目录下可以看到,我的是:C:/Program Files/WinRAR/WinRAR.chm,

rar命令和rar参数都可以看到,这里就不贴图了,

压缩文件命令:rar a rarPath srcPath -y,其中rarPath是要压缩到的文件地址,例如test.rar,srcPath是要压缩的文件或者文件夹,-y表示如果有提示确认,同意所有操作

解压文件命令:rar x rarPath destPath -y,其中rarPath是压缩文件的地址,例如test.rar,destPath是解压的路径,-y表示如果有提示确认,同意所有操作

const fs = require('fs');
const exec = require('child_process').exec;

/**
 * 执行cmd
 * @param cmd
 */
function execute(cmd) {
    exec(cmd, {encoding: 'binary'}, function (err, stdout, stderr) {
        if (err) {
            console.log(`err:${err}`);
        }
        if (stderr) {
            console.log(`stderr:${stderr}`);
        }
    });
}

/**
 * 判断文件或者路径是否存在
 * @param path
 * @param success 成功回调函数
 * @param error 错误回调函数
 */
function exist(path, success, error) {
    fs.exists(path, (exists) => {
        if (exists) {
            success && success();
        } else {
            console.log(`${path} not exist and create...`);
            error && error();
        }
    });
}

const rar = {
    /**
     * 压缩文件
     * @param config
     */
    compress: function (config) {
        let cmd = `rar a ${config.rarPath} ${config.srcPath} -y`;
        exist(config.srcPath, () => {
            execute(cmd);
        });
    },
    /**
     * 解压文件
     * @param config
     */
    decompress: function (config) {
        let cmd = `rar x ${config.rarPath} ${config.destPath} -y`;
        exist(config.rarPath, () => {
            exist(config.destPath, () => {
                execute(cmd);
            }, () => {
                fs.mkdir(config.destPath, (err) => {
                    if (err) {
                        console.log(err);
                    } else {
                        execute(cmd);
                    }
                });
            });
        });
    }
};

module.exports = rar;

测试代码:

测试结果:

猜你喜欢

转载自blog.csdn.net/u014264373/article/details/84753447