Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Node.js' fs.readFile() return a buffer instead of string?

I'm trying to read the content of test.txt(which is on the same folder of the Javascript source) and display it using this code:

var fs = require("fs");  fs.readFile("test.txt", function (err, data) {     if (err) throw err;     console.log(data); }); 

The content of the test.txt was created on nano:

Testing Node.js readFile()

And I'm getting this:

Nathan-Camposs-MacBook-Pro:node_test Nathan$ node main.js <Buffer 54 65 73 74 69 6e 67 20 4e 6f 64 65 2e 6a 73 20 72 65 61 64 46 69 6c 65 28 29> Nathan-Camposs-MacBook-Pro:node_test Nathan$  
like image 803
Nathan Campos Avatar asked Jun 23 '11 15:06

Nathan Campos


People also ask

Does readFileSync return a Buffer?

The readFileSync() function returns a Buffer .

What does Buffer mean in node js?

Buffers in Node. js is used to perform operations on raw binary data. Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities, but the difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not be resizable.

What does the readFile () method require?

readFile() Method. Parameters: The method accept three parameters as mentioned above and described below: filename: It holds the name of the file to read or the entire path if stored at other location. encoding: It holds the encoding of file.


2 Answers

From the docs:

If no encoding is specified, then the raw buffer is returned.

Which might explain the <Buffer ...>. Specify a valid encoding, for example utf-8, as your second parameter after the filename. Such as,

fs.readFile("test.txt", "utf8", function(err, data) {...}); 
like image 77
davin Avatar answered Sep 28 '22 04:09

davin


Try:

    fs.readFile("test.txt", "utf8", function(err, data) {...}); 

Basically, you need to specify the encoding.

like image 45
hvgotcodes Avatar answered Sep 28 '22 02:09

hvgotcodes