Created
August 16, 2017 09:38
-
-
Save yourtion/9332064324ef23c4a174f1b8853b54a6 to your computer and use it in GitHub Desktop.
Node.js create zip file with Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const express = require('express') | |
const app = express() | |
const archiver = require('archiver') | |
app.get('/', function(req, res) { | |
const archive = archiver('zip'); | |
archive.on('error', function(err) { | |
res.status(500).send({error: err.message}); | |
}); | |
//on stream closed we can end the request | |
archive.on('end', function() { | |
console.log('Archive wrote %d bytes', archive.pointer()); | |
}); | |
//set the archive name | |
res.attachment('archive-name.zip'); | |
//this is the streaming magic | |
archive.pipe(res); | |
const files = [__dirname + '/files/上午.png', __dirname + '/files/中午.json']; | |
for(const i in files) { | |
archive.file(files[i], { name: path.basename(files[i]) }); | |
} | |
archive.finalize(); | |
}); | |
app.listen(3010) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great. I experience a huge memory increase when carrying out zipping operation with archiver. Any hack on how to avoid such would be appreciated.