简体   繁体   中英

ENOENT: no such file or directory when running fs.readFile

Since starting my project I am having a difficulty with reading from file. I tried both with relative and absolute path. Tried both creating my own file and using fs.writeFileSync() to output one.

Interestingly fs.writeFileSync() works (file gets created with its content), but fs.readFile() can't find the file it created.

var fs = require('fs');
var path = require('path');

var content;
fs.writeFileSync('output.txt', 'test data', 'utf8');
fs.readFile('‎⁨output.txt', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);

Running the script produces error:

$ node script.js 
undefined
/path/to/project/script.js:6
        throw err;
        ^

Error: ENOENT: no such file or directory, open '‎⁨output.txt'

The access rights seem to be correct:

$ ls -l
total 104
-rw-r--r--  1 myusername  staff    634 Jan  3 14:24 script.js
-rw-r--r--  1 myusername  staff      8 Jan  3 14:23 output.txt

There are some (unprintable) characters prefixing the output.txt string in your call to fs.readFile() , which are causing the problem.

In my editor, I'm seeing this:

fs.readFile('<200e>⁨output.txt', function read(err, data)

"left-to-right mark (U+200E)"

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