简体   繁体   English

如何在Node.js中使用stream生成zip并将文件放入zip

[英]How to generate zip and put files into zip using stream in Node js

Currently, I tried to make zip file(or any format of compressed file) containing few files that I want to put into zip file.目前,我试图制作 zip 文件(或任何格式的压缩文件),其中包含一些我想放入 zip 文件的文件。

I thought it would work with adm-zip module.我认为它可以与 adm-zip 模块一起使用。
but I found out that the way adm-zip module put files into zip is buffer.但我发现 adm-zip 模块将文件放入 zip 的方式是缓冲区。
It takes a lot of memory when I put files that size is very huge.当我放置非常大的文件时,它需要很多 memory。 In the result, My server stopped working.结果,我的服务器停止工作。
Below is What I'd done.以下是我所做的。

var zip = new AdmZip();
zip.addLocalFile('../largeFile', 'dir1');  //put largeFile into /dir1 of zip
zip.addLocalFile('../largeFile2', 'dir1');
zip.addLocalFile('../largeFile3', 'dir1/dir2');
zip.writeZip(/*target file name*/ `./${threadId}.zip`);

Is there any solution to solve this situation?有什么办法可以解决这种情况吗?

to solve memory issue the best practice is to use streams and not load all files into memory for example解决 memory 问题的最佳做法是使用流,而不是将所有文件加载到 memory 例如

import {
  createReadStream,
  createWriteStream
} from 'fs'
import { createGzip } from 'zlib'

const [, , src, dest] = process.argv
const srcStream = createReadStream(src)
const gzipStream = createGzip()
const destStream = createWriteStream(dest)

srcStream
  .pipe(gzipStream)
  .pipe(destStream)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM