简体   繁体   中英

Error: ENOENT: no such file or directory, open '/moviedata.json'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM