What is this buffer when reading files in NODEJS?

1

I'm learning a bit of NodeJS . The last thing I learned was to read a file.

The question that left me with doubt is the following. When I use the readFile function with the second parameter being utf8 , the reading of the file occurs as expected (the same way it happens in PHP, where I come from).

Example:

var fs = require('fs')

fs.readFile('files/text.txt', 'utf8', function (err, data) {
    console.log(data)
});

However, when I do not pass the argument indicating that the reading will be like utf8 , things change:

fs.readFile('files/text.txt', function (err, data)
{
    console.log(data)
});

Output:

<Buffer 4c 6f 72 65 6d 20 69 70 73 75 6d 20 64 6f 6c 6f 72 20 73 69 74 20 61 6d 65 74 2c 20 63 6f 6e 73 65 63 74 65 74 75 72 20 61 64 69 70 69 73 69 63 69 6e 67 ...>

What is the meaning of this <Buffer> ?

    
asked by anonymous 07.12.2015 / 16:51

3 answers

2

This buffer is no more than the file read in "RAW" format. If you use .toString() it is converted into something you can read.

var fs = require('fs');

fs.readFile('files/text.txt', function (err, data) {
    if (err) throw err;
    console.log(data.toString());
});
    
07.12.2015 / 17:25
1

Responding roughly. This <buffer ...> corresponds to the binary data allocated in memory, memory is outside the V8 heap.

Buffer in NodeJS:

Buffer is the instance of a class in NodeJS. Each buffer is allocated in memory, as stated above. The Buffer is like an array of integers but it is not resizable. It has specific methods for working with binary data. Its values, which represent bytes in memory, have a limit of 0 a 255 (2 ^ 8 - 1) .

Reference: How to Use Buffers in Node.js

    
07.12.2015 / 17:35
0

Buffer is your file not parseted in hexadecimal format. You can pick up your answer and parse to form simple. Here is an example:

fs.readFile('files/text.txt', function (err, data) {
    console.log(JSON.parse(data));
});
    
07.12.2015 / 17:26