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:\test\18_20170313.rar D:\test\18_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:\test\18_20170313.rar D:\test\18_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:"源文件找不到"
            })
        }
    });
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM