im working in node Js. When im trying to load a file: moviedata.json, with this lines:
var allMovies = JSON.parse(fs.readFileSync('moviedata.json', 'utf8'));
Shows:
Error: ENOENT: no such file or directory, open './moviedata.json' at Error (native) at Object.fs.openSync (fs.js:640:18) at Object.fs.readFileSync (fs.js:508:33) at Object. (/Users/dortiz/Documents/NodeJS/pruebas/zw/aws/MoviesLoadData.js:13:31) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10)
Error: ENOENT: no such file or directory, open 'moviedata.json' at Error (native) at Object.fs.openSync (fs.js:640:18) at Object.fs.readFileSync (fs.js:508:33) at Object. (/Users/dortiz/Documents/NodeJS/pruebas/zw/aws/MoviesLoadData.js:13:31) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10)
The file to read its in same folder that js.
But im don't understand what im doing wrong
fs.readFileSync('moviedata.json', 'utf8')
will look for moviedata.json
in the directory from where you ran your application, not in the directory where your MoviesLoadData.js
file is located.
Suppose you ran node aws/MoviesLoadData.js
from /Users/dortiz/Documents/NodeJS/pruebas/zw
, fs.readFileSync('moviedata.json', 'utf8')
would look for moviedata.json
in /Users/dortiz/Documents/NodeJS/pruebas/zw
, not in /Users/dortiz/Documents/NodeJS/pruebas/zw/aws
If you were to run your script with my given example, you'd need to prepend the path to the json file to correctly reference it.
fs.readFileSync(__dirname + '/moviedata.json', 'utf8')
I'm not sure how you run your code, so my example may not work in your codebase, but hopefully understanding where you went wrong will help debug your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With