Error: ENOENT: no such file or directory

I’m using dataPath in NFT.js as below:

const dataPath = path.join(__dirname, '..', 'data', 'nfts.json');

Here’s the file structure:

File structure

This is my netlify.toml

    command = "yarn server"
    functions = "server"

The error is at the link:

This is the function called from NFT.js

nftRoutes.get('/nft', (request, response) => {
    fs.readFile(dataPath, 'utf8', (error, data) => {
        if (error) {
            throw error;

Hi @klaus.konstantino you can try path.join(process.cwd(), "server/data/nfts.json")

process.cwd() returns the current working directory, i.e. the directory from which you invoked the node command.

Therefore if the server folder is in the project root, then path.join(process.cwd(), "server/data/nfts.json") should give you the correct path to the nfts.json file

Let me know the outcome

I did update to const dataPath = path.join(process.cwd(), "server/data/nfts.json"); it’s still giving the same error.

@klaus.konstantino thanks for the feedback.
If possible can you share a repository of your project for me to help you with the debugging

Why not import the JSON in the function? JavaScript supports importing JSON just like importing other JS files. In any case, you can solve the issue using: How to Include Files in Netlify Serverless Functions, but I won’t recommend that in your use-case bcause:

  1. The file system is different in local and AWS Lambda. Figuring out the correct path could be tough.
  2. There’s an easier solution (as I mention, simply import the JSON in your JS file).

Can I use fs.writeFileSync with const dataPath = require('../data/nfts.json');

@klaus.konstantino No need to use fs.writeFileSync if you use dataPath = require('../data/nfts.json')
dataPath = require('../data/nfts.json') should read the json file and the variable dataPath will contain the json data.
Even though you can name variables with any name, instead of using dataPath as variable name a proper name will be nftsData as require('../data/nfts.json') reads the json data and sets it to the variable. It does not return the path.