WishIHadThreeGuns
WishIHadThreeGuns

Reputation: 1479

Return an array of files from NodeJS

I've been using res.sendFile to serve files using NodeJS such as

res.sendFile(path.resolve(fullpath))

but I want to return an array of the same. Something like

res.sendFile([path.resolve(fullpath),path.resolve(fullpath)])

but this returns an error.

How can I return an array of files?

Upvotes: 1

Views: 1074

Answers (2)

Vasileios Pallas
Vasileios Pallas

Reputation: 4867

if your target clients are web browsers, then you can't download multiple files, because the http protocol doesn't allow that. What you can do, is zip the files and send them back to the client.

Eg. You can use express-zip

The below example is from the documentation:

var app = require('express')();
var zip = require('express-zip');

app.get('/', function(req, res) {
  res.zip([
    { path: '/path/to/file1.name', name: '/path/in/zip/file1.name' }
    { path: '/path/to/file2.name', name: 'file2.name' }
  ]);
});

app.listen(3000);

Upvotes: 1

Gibor
Gibor

Reputation: 1721

res.sendFile gets a single string as an argument. You can't pass it an array, no matter what you do.

What you can do, is build the array beforehand, and use array.forEach to send each file seperately:

paths = [path.resolve(fullpath1),path.resolve(fullpath2)];
paths.forEach( path => res.sendFile(path) );

Upvotes: 0

Related Questions