简体   繁体   中英

I tried requiring nodejs fs module and keep getting the error below, how do I go about it please?

Here is my code:

var fs= require('fs');
 var readMe = fs.readFileSync('readMe.txt', 'utf-8');     // method to read file in node..note the  'sync' maintains strict order of code
console.log('readMe.txt');

However, when I run it I get this error:

C:\visual studio code\nodeJS>node "c:\visual studio code\nodeJS\netNinja\app.js"internal/fs/utils.js:308
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'readMe.txt'
?[90m    at Object.openSync (fs.js:476:3)?[39m
?[90m    at Object.readFileSync (fs.js:377:35)?[39m
    at Object.<anonymous> (c:\visual studio code\nodeJS\netNinja\app.js:105:20)
?[90m    at Module._compile (internal/modules/cjs/loader.js:1063:30)?[39m
?[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:928:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:769:14)?[39m
?[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)?[39m
?[90m    at internal/main/run_main_module.js:17:47?[39m {
  errno: ?[33m-4058?[39m,
  syscall: ?[32m'open'?[39m,
  code: ?[32m'ENOENT'?[39m,
  path: ?[32m'readMe.txt'?[39m
}

The error itself is pretty specific. ENOENT means that the file readMe.txt is not found in the current working directory and thus fs.readFileSync() throws an exception.

So, either that file does not exist at all or it's not in the current working directory (and thus you need a path to it) or there's some sort of permission issue that keeps it from being visible (this last one is less likely the issue).

If you want to see where nodejs is looking for a file with no path on it, you can do:

console.log(process.cwd());

And that will show you what the current working directory is in your nodejs app.

Or, you can do this to see where it is looking for your file:

const path = require('path');
console.log(path.resolve("readMe.txt"));

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