user4445419
user4445419

Reputation:

Cannot read file with nodejs

I use the following code to read a file from my desktop. When I run the server and use some request I don't see anything in the debugger.

What am I missing here?

fs = require('fs');   
fs.readFile('‪C:\Users\i123\Desktop\test.txt', 'utf8', function (err,data) {
     if (err) {
         return console.log(err);
     }
     console.log(data);
     res.send(data);
});

Upvotes: 1

Views: 4673

Answers (2)

kirubel Tamene
kirubel Tamene

Reputation: 19

In my case, I was using Documentation

const fs = require('node:fs/promises');

and when I changed it to this, it worked.

const fs = require('node:fs');

Upvotes: 0

jfriend00
jfriend00

Reputation: 707148

It's hard to know all the things that might be wrong here since you only show a small piece of your code, but one thing that is wrong is the filename string. The \ character in Javascript is an escape mechanism so that the string '‪C:\Users\i123\Desktop\test.txt' is not what you want it to be. If you really need backslashes in the string for a Windows filename, then you would need to use this:

'‪C:\\Users\\i123\\Desktop\\test.txt'

Other things I notice about your code:

  1. Returning a value from the readFile() callback does nothing. It just returns a value back into the bowels of the async file I/O which does nothing.

  2. When you get a file error, you aren't doing anything with the res which presumably means this route isn't doing anything and the browser will just be left waiting.

Upvotes: 1

Related Questions