如何将Node.js中的.zip / .rar文件解压缩到一个文件夹中

时间:2014-01-27 13:27:38

标签: node.js

我现在正在使用zlib和fstream进行压缩并发送到客户端,现在我需要将存档(可能包含子文件夹)解压缩到维护文件夹结构的文件夹中。我该怎么做?

5 个答案:

答案 0 :(得分:11)

有很多节点模块可以为您完成此操作。其中之一是node-unzip。您可以将.zip文件解压缩到一个简单的目录。

fs.createReadStream('path/to/archive.zip').pipe(unzip.Extract({ path: 'output/path' }));

进一步阅读:https://github.com/EvanOxfeld/node-unzip

答案 1 :(得分:1)

Rar是一个闭源软件。你可以做到的唯一方法 - 安装命令行rar(rar.exe或rar的linux版本,在大多数平台上都可用)并通过以下方式调用它:

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

exec("rar.exe x file.rar", function (error) {
    if (error) {
     // error code here
    } else {
      // success code here
    }
});

答案 2 :(得分:1)

你可以使用这个神奇的模块http://node-machine.org/machinepack-zip

用于解压缩zip文件中包含目录结构的zip文件

import sys, signal, socket
from PyQt4 import QtCore, QtNetwork

class SignalWakeupHandler(QtNetwork.QAbstractSocket):

    def __init__(self, parent=None):
        super().__init__(QtNetwork.QAbstractSocket.UdpSocket, parent)
        self.old_fd = None
        # Create a socket pair
        self.wsock, self.rsock = socket.socketpair(type=socket.SOCK_DGRAM)
        # Let Qt listen on the one end
        self.setSocketDescriptor(self.rsock.fileno())
        # And let Python write on the other end
        self.wsock.setblocking(False)
        self.old_fd = signal.set_wakeup_fd(self.wsock.fileno())
        # First Python code executed gets any exception from
        # the signal handler, so add a dummy handler first
        self.readyRead.connect(lambda : None)
        # Second handler does the real handling
        self.readyRead.connect(self._readSignal)

    def __del__(self):
        # Restore any old handler on deletion
        if self.old_fd is not None and signal and signal.set_wakeup_fd:
            signal.set_wakeup_fd(self.old_fd)

    def _readSignal(self):
        # Read the written byte.
        # Note: readyRead is blocked from occuring again until readData()
        # was called, so call it, even if you don't need the value.
        data = self.readData(1)
        # Emit a Qt signal for convenience
        self.signalReceived.emit(data[0])

    signalReceived = QtCore.pyqtSignal(int)

app = QApplication(sys.argv)
SignalWakeupHandler(app)

signal.signal(signal.SIGINT, lambda sig,_: app.quit())

sys.exit(app.exec_())

//解压缩指定的.zip文件,并将解压缩的文件/目录写为指定目标目录的内容。

var Zip = require('machinepack-zip');

用于下载远程文件并解压缩,您可以使用以下代码:

Zip.unzip({
   source: '/Users/mikermcneil/stuff.zip',
   destination: '/Users/mikermcneil/my-stuff',
}).exec(callbackSuccess, callbackFail );

注意:删除不必要的模块。

答案 3 :(得分:0)

使用node js decompress-zip,首先使用npm安装它:

npm install decompress-zip --save

然后您需要它:

const DecompressZip = require('decompress-zip');

最后,您可以通过以下方式使用它:

let unzipper = new DecompressZip( absolutePathFileZip );

必须指定要提取的目录:

unzipper.extract({
    path: pathToExtract
}); 

另外,您可以使用以下内容进行更好的控制:

处理错误:

unzipper.on('error', function (err) {
      console.log('event error')
 });

在提取所有内容时通知

unzipper.on('extract', function (log) {
    console.log('log es', log);
});

通知解压缩文件的“进度”:

unzipper.on('progress', function (fileIndex, fileCount) {
    console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);         
});

答案 4 :(得分:0)

如果有人正在寻找异步等待方式语法:

const request = require('request');
const unzip = require('unzip');

await new Promise(resolve =>
            request('url')
                .pipe(fs.createWriteStream('path/zipfilename'))
                .on('finish', () => {
                    resolve();
                }));

await new Promise(resolve =>
            fs.createReadStream('path/filename')
                .pipe(unzip.Extract({ path: 'path/extractDir }))
                .on('close', ()=>{
                    resolve()
                }));