Reading multiple files through API call
Answered
Sun bear posted this in #help-forum
Sun bearOP
So I'm using Next 16 and have an API route setup. I'm trying to take query parameters and parse them into an array of files that need to be read into a single variable and returned. In other words, I have "file1", "file2", "file3" etc, and I want to return something like this as a string:
I've gotten it to parse out the filenames and can load them, but I'm not competent enough with promises yet to work through how to return the contents of the file in such a way that I can build a single string from all of them without states. Thoughts?
<file1 contents>
<file2 contents>
<file3 contents>I've gotten it to parse out the filenames and can load them, but I'm not competent enough with promises yet to work through how to return the contents of the file in such a way that I can build a single string from all of them without states. Thoughts?
Answered by Pacific sand lance
you can easly read files using
node:fs/promises module, Promise.all takes an array of promises and waits for all of them to resolve, then returns values while preserving order3 Replies
Pacific sand lance
assume parsed files are in
files array thenconst contents = await Promise.all(files.map(file => someFunctionThatReturnsPromiseWithFileContent(file))); // string[];
const data = contents.join("\n"); // string
// return text response herePacific sand lance
you can easly read files using
node:fs/promises module, Promise.all takes an array of promises and waits for all of them to resolve, then returns values while preserving orderAnswer
Sun bearOP
Promise.all is what I was missing! Thanks!