nodejs rar/zip加密压缩、解压缩

1、shell/cmd命令行压缩解压缩

(1)zip压缩解压缩

zip压缩:zip -rP{密码} <目标文件.zip> <源文件> //默认覆盖现有文件

zip解压缩:zip -oP{密码} <源文件.zip> //默认覆盖现有文件

(2)rar压缩解压缩

说明: linux需要下载rarlinux,然后压缩,make编译后,即可使用。

rar压缩:rar a -p{密码} <目标文件.rar> <源文件> -y //默认覆盖现有文件

例如:rar a -p123456 abc.rar abc

rar解压缩:rar x -p{密码 } <源文件.rar> -y //保留源文件路径,默认覆盖现有文件

例如:rar x -p123456 abc.rar -y

2、如何通过nodejs执行shell/cmd命令

说明:通过child_process模块

var exec = require('child_process').exec;  //引入child_process模块

exports.execCmd = function(cmdStr,next){
    exec(cmdStr,function(err,stdout,stderr){
        next({
            err:err,
            stdout:stdout,
            stderr:stderr
        });
    });
}

 

3、封装成方法

rar解压缩:

/*
方法名:rar解压缩
参数:
 password
 zipFilePath
 tgtFilePath
例如:
 var password ="20170313",
 zipFilePath ="D:/test/18_20170313.rar",
 srcFilePath = "D:/test/18_20170313";
 cmdStr = "rar x -P20170313 D:	est18_20170313.rar D:	est18_20170313 -y"

 * */
var fs = require("fs");
var exec = require('child_process').exec;

exports.unrar = function(param,next){
    console.log("param:",param);
    var cmdStr = "rar x -P"+param.password+" "+param.zipFilePath+" "+param.tgtFilePath+" -y";
    console.log("cmd:",cmdStr);
    fs.exists(param.tgtFilePath, function(exists) {  //判断路径是否存在
        //console.log(">> exists:",exists);
        if(exists) {
            exec(cmdStr,function(err,stdout,stderr){  //执行命令行
                fs.readdir(param.filesPathInPro,next);
            });
        } else {
            fs.mkdir(param.tgtFilePath,function(){  //创建目录
                exec(cmdStr,function(err,stdout,stderr){  //执行命令行
                    fs.readdir(param.filesPathInPro,next);
                });
            });
        }
    });
}
 

rar压缩:

/*
方法名:rar压缩
参数:
password
zipFilePath
srcFilePath
例如:
var password ="20170313",
zipFilePath ="D:/test/18_20170313.rar",
srcFilePath = "D:/test/18_20170313";
cmdStr ="rar a -ep -P20170313 D:	est18_20170313.rar D:	est18_20170313"
 * */

var fs = require("fs");
var exec = require('child_process').exec;

exports.rar = function(param,next){
    var cmdStr = 'rar a -ep -P'+param.password+' '+param.zipFilePath+' '+param.srcFilePath+' -y';
    console.log(">> cmdStr:",cmdStr);
    fs.exists(param.srcFilePath, function(exists) {  //判断路径是否存在
        if(exists) {
            exec(cmdStr,next);
        } else {
            next({
                code:400,
                msg:"源文件找不到"
            })
        }
    });
}