NIKHIL C M
NIKHIL C M

Reputation: 4236

How to pipe a WriteStream concatenating an extension?

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 ?

Upvotes: 0

Views: 818

Answers (2)

NIKHIL C M
NIKHIL C M

Reputation: 4236

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();

    });

Upvotes: 1

robertklep
robertklep

Reputation: 203529

You can use res.attachment() to both set the filename of the download, and also its mime-type:

router.get('/archive/*', function (req, res) {
  res.attachment('archive.zip');
  ...
});

Upvotes: 1

Related Questions