I am new in NodeJS. I know we can stream data to the client by using pipe() method.
Here is the snippet of the code
router.get('/archive/*', function (req, res) {
var decodedURI = decodeURI(req.url);
var dirarr = decodedURI.split('/');
var dirpath = path.join(dir, dirarr.slice(2).join("/"));
console.log("dirpath: " + dirpath);
var archive = archiver('zip', {
zlib: {level: 9} // Sets the compression level.
});
archive.directory(dirpath, 'new-subdir');
archive.on('error', function (err) {
throw err;
});
archive.pipe(res)
archive.on('finish', function () {
console.log("finished zipping");
});
archive.finalize();
});
when I use a get request the zipped file downloaded but without any extension. I know its because I am piping a writestream into the response. Is there anyway pipe it with a .zip extension ? Or How can I send the zip file without building the zip file in HDD ?
One of the ways is to change Headers before piping,
res.setHeader("Content-Type", "application/zip");
res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip');
For the Given Code,
router.get('/archive/*', function (req, res) {
var decodedURI = decodeURI(req.url);
var dirarr = decodedURI.split('/');
var dirpath = path.join(dir, dirarr.slice(2).join("/"));
var output = fs.createWriteStream(__dirname + '/7.zip');
var archive = archiver('zip', {
zlib: {level: 9} // Sets the compression level.
});
archive.directory(dirpath, 'new-subdir');
archive.on('error', function (err) {
throw err;
});
res.setHeader("Content-Type", "application/zip");
res.setHeader('Content-disposition' ,'attachment; filename=downlaod.zip');
archive.pipe(res);
archive.finalize();
});