node采用【child_process】实现Linux环境下压缩包自动解压

Ubuntu环境安装解压包

如果你不知道安装什么包,直接执行解压命令,Ubuntu会提示你安装的。

JS功能包

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

// unrar  <源文件.rar>  <解压文件夹路径>
exports.unrar = function(param){
    console.log("param:",param);
    var cmdStr = "rar x "+ 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,getMainFile);
            });
        } else {
            fs.mkdir(param.tgtFilePath,function(){  //创建目录
                exec(cmdStr,function(err,stdout,stderr){  //执行命令行
                    fs.readdir(param.filesPathInPro,getMainFile);
                });
            });
        }
    });
};
// unzip  <源文件.zip>  <解压文件夹解压文件夹路径>
exports.unzip = function(param){
    console.log("param:",param);
    var cmdStr = "unzip "+" "+param.zipFilePath +" -d "+ param.tgtFilePath;
    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,getMainFile);
            });
        } else {
            fs.mkdir(param.tgtFilePath,function(){  //创建目录
                exec(cmdStr,function(err,stdout,stderr){  //执行命令行
                    fs.readdir(param.filesPathInPro,getMainFile);
                });
            });
        }
    });
};

其中getMainFile是处理解压后的文件函数,也可以不处理,注释掉就OK了。

调用js功能包

  const exec = require('../common/exec');
  var zipFilePath = path.join(UserFilePath, "/" + file.name);
            var param = {
                zipFilePath: zipFilePath,
                tgtFilePath: path.join(UserFilePath, "/" + file_name),
                filesPathInPro: path.join(UserFilePath, "/" + file_name)
            };
            if (ext == "rar") {
                exec.unrar(param);
            }
            if (ext == "zip") {
                exec.unzip(param);
            }

注意其中各种路径的设置,按照自己的文件位置修改一下。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_18144905/article/details/85272660