I’m having an issue in a function with fs (file system) in my node project. In this support thread (List files in another directory from lambda function - #2 by coelmay), it seems that maybe the person had a similar issue, but I’m struggling to land on a workable solution. Here’s what’s going on…
So, I have an API function that takes a param at the end like this:
https://[myapp].netlify.app/.netlify/functions/api/[id]
It then builds a file path like this …
const filePath = ‘…/mydirectory/’ + id;
… and then I need it to go grab some static JSON from a file at that location …
const data = fs.readFileSync(filePath, ‘utf8’);
… and then it would return the data …
return { statusCode: 200, body: data };
If I hard-code the file path, it’ll go find that file. But if I need to dynamically do it as shown here, it will always give me a “file not found” error.
The thread linked to above suggests compiling all of the data into one file and then requiring that. However, I have 10,000 different JSON files in that directory. So, I don’t think it’s practical to include 50mb of data just so the program can access one small chunk.
I know tha these files exist, as I can see them uploaded in the deploy logs. I guess, within a function, though, they seem to need to be required. Thus, I’m stuck. Any thoughts on how to proceed? Ironicaly, I was thinking, “well, I could put that JSON data on an API and fetch it easily” but … THIS is my API, lol, so it s/b doable right from here somehow. Anyway, I’m kinda new to node, so maybe I’m just missing something). But, what should I do if I need my API to pull from 10,000 JSON files like this? Whole different approach? Or, is it possible for this function to work?
Many thanks,
-Jim