0

so I was making a program that scrapes a website and stores the data in json format with fs.writeFile and another program that read from the stored json using fs.readFile, but the fs.readFile returns "ENOENT: no such file or directory, open...."

fs.readFile("./json/productVariables.json","utf-8",(err, data) => {
        if (err) {
          console.log("could not read the JSON file " + err);
        } else {
          const productVariable = JSON.parse(data);
}});


I've even wrapped it with fs.access to check if the file exists, but still returns the same error

fs.access("productVariables.json", fs.constants.F_OK, (err) => {
  if (err) {
    console.log("JSON file doesn't exist " + err);
  }
  fs.readFile(
    "./json/productVariables.json",
    "utf-8",
    (err, data) => {
      if (err) {
        console.log("could not read the JSON file " + err);
      } else {
        const productVariable = JSON.parse(data);
      }
    }
  )
})

I've checked the file path and it's all correct, and I can literally see it in the directory

when I use require to parse the JSON file it works, but I want to use fs to check is the file is present and to parse from the file if it exists. Why is it returning no such file or directory error when the file is actually there

Edit

I wrote the JSON file with fsPromises like this

await fsPromises.writeFile(
      path.join(__dirname, "json", "productVarables.json"),
      JSON.stringify(variables),
      (err) => {
        if (err) {
          console.log("error while writing the JSON" + err);
        } else {
          console.log("successfuly written the JSON file");
        }
      }
    );

and when I try to read it using fsPromises like this

await fsPromises.readFile(
      path.join(__dirname, "json", "productVarables.json"),
      "utf-8",
      (err, data) => {
        if (err) {
          console.log(err);
        } else {
          console.log(data);
        }
      }
    );

I get the following error

node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: ENOENT: no such file or directory, open 'D:\desktop\Project\Node\Scraper\json\productVariables.json'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'D:\\desktop\\Project\\Node\\Scraper\\json\\productVariables.json'
}
boom pow
  • 181
  • 9
  • try using fs promises to make sure the write is finished before reading. https://stackoverflow.com/a/53753481/11616708 – smcrowley Jul 22 '22 at 21:11
  • You have two different paths. You are checking `"./productVariables.json"` but then trying to read `"./json/productVariables.json"` – derpirscher Jul 22 '22 at 21:49

0 Answers0