Node.js 中的 Zip 档案

发布于 2024-11-03 00:19:29 字数 57 浏览 0 评论 0原文

我想创建一个 zip 存档并将其解压缩到 node.js 中。

我找不到任何节点实现。

I want to create a zip archive and unzip it in node.js.

I can't find any node implementation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

相思碎 2024-11-10 00:19:29

node-core 内置了 zip 功能: http://nodejs.org/api/zlib.html

使用它们:

var zlib = require('zlib');
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');

inp.pipe(gzip).pipe(out);

node-core has built in zip features: http://nodejs.org/api/zlib.html

Use them:

var zlib = require('zlib');
var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var out = fs.createWriteStream('input.txt.gz');

inp.pipe(gzip).pipe(out);
半透明的墙 2024-11-10 00:19:29

我最终这样做了(我正在使用 Express)。我正在创建一个 ZIP,其中包含给定目录 (SCRIPTS_PATH) 上的所有文件。

我只在 Mac OS X Lion 上对此进行了测试,但我想它在安装了 Cygwin 的 Linux 和 Windows 上也能正常工作。

var spawn = require('child_process').spawn;
app.get('/scripts/archive', function(req, res) {
    // Options -r recursive -j ignore directory info - redirect to stdout
    var zip = spawn('zip', ['-rj', '-', SCRIPTS_PATH]);

    res.contentType('zip');

    // Keep writing stdout to res
    zip.stdout.on('data', function (data) {
        res.write(data);
    });

    zip.stderr.on('data', function (data) {
        // Uncomment to see the files being added
        // console.log('zip stderr: ' + data);
    });

    // End the response on zip exit
    zip.on('exit', function (code) {
        if(code !== 0) {
            res.statusCode = 500;
            console.log('zip process exited with code ' + code);
            res.end();
        } else {
            res.end();
        }
    });
});

I ended up doing it like this (I'm using Express). I'm creating a ZIP that contains all the files on a given directory (SCRIPTS_PATH).

I've only tested this on Mac OS X Lion, but I guess it'll work just fine on Linux and Windows with Cygwin installed.

var spawn = require('child_process').spawn;
app.get('/scripts/archive', function(req, res) {
    // Options -r recursive -j ignore directory info - redirect to stdout
    var zip = spawn('zip', ['-rj', '-', SCRIPTS_PATH]);

    res.contentType('zip');

    // Keep writing stdout to res
    zip.stdout.on('data', function (data) {
        res.write(data);
    });

    zip.stderr.on('data', function (data) {
        // Uncomment to see the files being added
        // console.log('zip stderr: ' + data);
    });

    // End the response on zip exit
    zip.on('exit', function (code) {
        if(code !== 0) {
            res.statusCode = 500;
            console.log('zip process exited with code ' + code);
            res.end();
        } else {
            res.end();
        }
    });
});
且行且努力 2024-11-10 00:19:29

您可以尝试 node-zip npm 模块。

它将 JSZip 移植到节点,以压缩/解压缩 zip 文件。

You can try node-zip npm module.

It ports JSZip to node, to compress/uncompress zip files.

林空鹿饮溪 2024-11-10 00:19:29

您可以使用 archiver 模块,这对我非常有帮助,这是一个示例:

var Archiver = require('archiver'),
    fs = require('fs');
app.get('download-zip-file', function(req, res){    
    var archive = Archiver('zip');
    archive.on('error', function(err) {
        res.status(500).send({error: err.message});
    });
    //on stream closed we can end the request
    res.on('close', function() {
        console.log('Archive wrote %d bytes', archive.pointer());
        return res.status(200).send('OK').end();
    });
    //set the archive name
    res.attachment('file-txt.zip');
    //this is the streaming magic
    archive.pipe(res);
    archive.append(fs.createReadStream('mydir/file.txt'), {name:'file.txt'});
    //you can add a directory using directory function
    //archive.directory(dirPath, false);
    archive.finalize();
});

You can use archiver module, it was very helpful for me, here is an example:

var Archiver = require('archiver'),
    fs = require('fs');
app.get('download-zip-file', function(req, res){    
    var archive = Archiver('zip');
    archive.on('error', function(err) {
        res.status(500).send({error: err.message});
    });
    //on stream closed we can end the request
    res.on('close', function() {
        console.log('Archive wrote %d bytes', archive.pointer());
        return res.status(200).send('OK').end();
    });
    //set the archive name
    res.attachment('file-txt.zip');
    //this is the streaming magic
    archive.pipe(res);
    archive.append(fs.createReadStream('mydir/file.txt'), {name:'file.txt'});
    //you can add a directory using directory function
    //archive.directory(dirPath, false);
    archive.finalize();
});
冷了相思 2024-11-10 00:19:29

如果您只需要解压缩, node-zipfile 看起来比 节点存档。它的学习曲线肯定更小。

If you only need unzip, node-zipfile looks to be less heavy-weight than node-archive. It definitely has a smaller learning curve.

岁月无声 2024-11-10 00:19:29

adm-zip

这是一个纯 JavaScript 库,用于读取、创建和修改内存中的 zip 存档。

它看起来不错,但有点小问题。我在解压缩文本文件时遇到一些问题。

adm-zip

It's a javascript-only library for reading, creating and modifying zip archives in memory.

It looks nice, but it is a little buggy. I had some trouble unzipping a text file.

断舍离 2024-11-10 00:19:29

我使用“archiver”来压缩文件。以下是 Stackoverflow 链接之一,展示了如何使用它,使用归档器压缩文件的 Stackoverflow 链接

I have used 'archiver' for zipping files. Here is one of the Stackoverflow link which shows how to use it, Stackoverflow link for zipping files with archiver

烟酉 2024-11-10 00:19:29

我发现围绕 7-zip 进行我自己的包装是最简单的,但是您也可以轻松地使用 zip 或运行时环境中可用的任何命令行 zip 工具。这个特定的模块只做一件事:压缩目录。

const { spawn } = require('child_process');
const path = require('path');

module.exports = (directory, zipfile, log) => {
  return new Promise((resolve, reject) => {
    if (!log) log = console;

    try {
      const zipArgs = ['a', zipfile, path.join(directory, '*')];
      log.info('zip args', zipArgs);
      const zipProcess = spawn('7z', zipArgs);
      zipProcess.stdout.on('data', message => {
        // received a message sent from the 7z process
        log.info(message.toString());
      });

      // end the input stream and allow the process to exit
      zipProcess.on('error', (err) => {
        log.error('err contains: ' + err);
        throw err;
      });

      zipProcess.on('close', (code) => {
        log.info('The 7z exit code was: ' + code);
        if (code != 0) throw '7zip exited with an error'; // throw and let the handler below log it
        else {
          log.info('7zip complete');
          return resolve();
        }
      });
    }
    catch(err) {
      return reject(err);
    }
  });
}

像这样使用它,假设您已将上述代码保存到 zipdir.js 中。第三个 log 参数是可选的。如果您有自定义记录器,请使用它。或者完全删除我讨厌的日志语句。

const zipdir = require('./zipdir');

(async () => {
  await zipdir('/path/to/my/directory', '/path/to/file.zip');
})();

I've found it easiest to roll my own wrapper around 7-zip, but you could just as easily use zip or whatever command line zip tool is available in your runtime environment. This particular module just does one thing: zip a directory.

const { spawn } = require('child_process');
const path = require('path');

module.exports = (directory, zipfile, log) => {
  return new Promise((resolve, reject) => {
    if (!log) log = console;

    try {
      const zipArgs = ['a', zipfile, path.join(directory, '*')];
      log.info('zip args', zipArgs);
      const zipProcess = spawn('7z', zipArgs);
      zipProcess.stdout.on('data', message => {
        // received a message sent from the 7z process
        log.info(message.toString());
      });

      // end the input stream and allow the process to exit
      zipProcess.on('error', (err) => {
        log.error('err contains: ' + err);
        throw err;
      });

      zipProcess.on('close', (code) => {
        log.info('The 7z exit code was: ' + code);
        if (code != 0) throw '7zip exited with an error'; // throw and let the handler below log it
        else {
          log.info('7zip complete');
          return resolve();
        }
      });
    }
    catch(err) {
      return reject(err);
    }
  });
}

Use it like this, assuming you've saved the above code into zipdir.js. The third log param is optional. Use it if you have a custom logger. Or delete my obnoxious log statements entirely.

const zipdir = require('./zipdir');

(async () => {
  await zipdir('/path/to/my/directory', '/path/to/file.zip');
})();
遇到 2024-11-10 00:19:29

如果你不想使用/学习一个库,你可以使用node来控制通过执行子进程来使用 zip 命令行工具

虽然我建议学习像 Emmerman 提到的那样的库

If you don't want to use/learn a library, you could use node to control the zip commandline tools by executing child processes

Though I'd recommend learning a library like the one mentioned by Emmerman

做个少女永远怀春 2024-11-10 00:19:29

您可以使用支持node.js和.NET进程内互操作的 edge.js 模块,并且然后调用 .NET 框架的 ZipFile 类,它允许您操作 ZIP 档案。这是使用edge.js创建ZIP包的完整示例。另请查看使用edge.js解压示例

You can use the edge.js module that supports interop between node.js and .NET in-process, and then call into .NET framework's ZipFile class which allows you to manipulate ZIP archives. Here is a complete example of creating a ZIP package using edge.js. Also check out the unzip example using edge.js.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文