Pooyan
Pooyan

Reputation: 490

ENOENT: no such file or directory, open 'Filename'

I was requiring some data from a .json file but I am getting this error:

Error: ENOENT: no such file or directory, open '../Jsons/eshop.json'
    at Object.openSync (node:fs:585:3)
    at Object.readFileSync (node:fs:453:35)
    at Object.execute (C:\Users\Pooyan\Desktop\PDM Bot Main\commands\shop.js:9:24)
    at module.exports (C:\Users\Pooyan\Desktop\PDM Bot Main\events\guild\message.js:114:15)
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: '../Jsons/eshop.json'
}

My code:

let shop_data = JSON.parse(Buffer.from(fs.readFileSync('../Jsons/eshop.json')).toString());
    let index = (args[0] || "1");
    let page = shop_data.pages[index];

I think that's all you need, but if any other code was needed, comment it. I am using discord.js v13 and node.js 16

Upvotes: 6

Views: 18413

Answers (3)

hhelsinki
hhelsinki

Reputation: 84

I suggest the problem came from module reading path, if your case is fs.readFile is working find until you call it from root index.js

If Your Path
-index.js
./services/getData.js (fs.readFile func is calling here)
./json/eshop.json

Inside index.js

app.get( '/eshop', getData);

Have to change view side of ./services/getData.js to index.js

'../json/eshop.json'

To

'./json/eshop.json'

I got the same issue, this fix me, no need to install anything.

Upvotes: 0

You need to use path module and join the folder names to define the json file location.

Let,the data is in following directory. ( NewProject/data/eshop.json )

  • NewProject
    • Project root directory
    • data
      • eshop.json

You want to access the eshop.json file from any file under the project directory.

Solution is below:

const fs = require('fs')
const path = require('path');
const directory = path.join('data', 'eshop.json')
// directory ==> data\eshop.json
exports.getRandomUserService = () => {
     const jsonData = fs.readFileSync(directory);
     const eshop= JSON.parse(jsonData);
     console.log('eshop data from json file: ',eshop);
}

Upvotes: 2

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

The issue is with the path. It seems the path is invalid for the given eshop.json file or there might be any spelling mistake in the path.

fs.readFileSync takes the relative path:

  • test.js
  • JSON
    • sampleJSON
      • eshop.json
fs.readFileSync('./JSON/sampleJSON/eshop.json');

Upvotes: 1

Related Questions