1

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?

1
  • That is not possible. What you can do is create an archive of files and then transfer the archive Commented Sep 4, 2019 at 8:31

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Hmm. When using this I only see a single file through Postman!
@WishIHadThreeGuns of course, you do send each file seperately at the end. Like I said, there is no way to send multiple raw files using res.sendfile. You can either send them one-by-one with forEach on paths array, or use the other suggested answer- to zip them and send them compressed. You will have to make changes on the client side, so it will be able to get the zip file and decompress it.
ZIP files aren't an option, mobile backend using this to receive HTML pages and then render. I can send as a JSON array and then render but this does not feel ideal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.