1
fs.readFile() showing weird string to console in Node Js
AAnonymity (0)

fs.readFile() showing weird string to console in Node Js

I am trying to read a text file and print out the results in the console, but whenever I try, I get a weird string rather than the text. Here is my text file:

Hello World!
I code JS.

And here is index.js:

const fs = require(‘fs’);
fs.readFile(‘text.txt’, (err, data) => {
  console.log(data);
});
And here is the output:
`<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 0a 49 20 63 6f 64 65 20 4a 53 2e>`

___All help appreciated!___
You are viewing a single comment. View All
2
vedprad1 (461)

The solution is simple.
When fs.readFile() only has two parameters, it will return a buffer.
The solution is to add a parameter between the file name and the callback, like this:

const fs = require(‘fs’);
fs.readFile(‘text.txt’, ‘utf-8’ (err, data) => {
  console.log(data);
});

If this answers your question, please check the checkmark on the left side of this message. Thanks and Good Luck!