List files in another directory from lambda function

I have a netlify function that needs to read all the files in a directory I created and then do some logic with that data. Everything works fine with my local build, the lambda function finds the files and does its job but when I publish it cannot find the directory. I am assuming it is because the server doesn’t keep the same directory structure.

How do I find the path to my other directory with the files?
Or how do I tell netlify that I need a certain function to access that directory?

# Folder Structure
- lambda
  - read_dir_func.js
- route_data
  - home.js
  - contact.js
  - missing.js
  ... etc ...
# read_dir_func.js
const fs = require('fs');
const path = require('path');
const ROOT = path.join( __dirname, '../' );

fs.readdir( path.join( ROOT, '/route_data' ), ( err, list ) => {
   if( err ) return console.error( err );
  .... logic ....
});
# Server Response
[Error: ENOENT: no such file or directory, scandir '/var/task/route_data'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '/var/task/route_data'
}

Hi @sv_vmh_dev ,

Possibly these posts may help you:

Thanks for the resources. So yeah, Denis pretty much answered my question.

But in my case, I think I will go with the suggestion from this other post:

For anyone that comes to this post. I recommend that you consider if can you pre-compile multiple files into 1 file and just require that 1 file. For example, instead of serving multiple json files based on some logic, merge those json files into 1 file using something like bash.

# Folder Structure with compiled file
- route_data
  - compiled.js
    {
       "home": .... data from file ....
       "contact": .... data from file ....
       "missing": .... data from file ....
    }
  - home.js
  - contact.js
  - missing.js
# read_dir_func.js
const fs = require('fs');
const path = require('path');
const compiled = require('../route_data/compiled.js');

.... logic ....
1 Like