A
A
atumbochka2022-04-09 13:07:32
JavaScript
atumbochka, 2022-04-09 13:07:32

How to send all files from a folder to a website from a server?

I need that when the site loads, it displays all the mp3 files in the folder, that is, they must find their src. If I just sent 1 specific file, I would do it like this:

app.get("/getFile", (req, res) => {
    res.sendFile(path.join(__dirname, "uploads",  "имя файла"));
});

But in my case, it is required to download all the files in the folder, that is, I don’t know their names and number, since the user himself decides what and how much to download. I tried to do the following, for example, upload the latest file without specifying a specific name:
const music = fs.readdirSync(path.join(__dirname, "uploads"));
app.get("/getFile", (req, res) => {
    res.sendFile(path.join(__dirname, "uploads", music[music.length - 1]));
});

And it worked, but again, what to do with several files, I can’t write several res.sendFile at once in one request, I can’t create several requests in advance, because I don’t know how many files there will be in the folder. Yes, and it will be stupid, because if the user uploads, say, 500 files, I will not make 500 get requests in the server file. That is, it is necessary that one request somehow "issues" src to several files. I hope my problem is clear.
I also tried to do it differently: a post-request from the site sends the number of the desired file, that is, i in the for loop, and a file with this number arrives (you just need to subtract 1), that is, I also learned to accept a specific file, but the main the problem remains: how to send multiple files?
I think that there is some kind of property or method that I don't know about, but I didn't seem to find anything like that. Maybe someone faced such a problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
black1277, 2022-04-09
@atumbochka

Most likely you need a method for distributing static files:

app.use(express.static(path.join(__dirname, 'public')))

all files in the public folder (you can set your own) can be received by the client. It is only necessary to form a list of existing files and issue their url to the front.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question