What is this <Buffer> in reading files in NODEJS?

Asked

Viewed 978 times

1

I’m learning a little bit about NodeJS. The last thing I learned was reading a file.

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

Example:

var fs = require('fs')

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

However, when I don’t pass the argument indicating that the reading will be like utf8, things change:

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

Exit:

<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>?

3 answers

2


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

var fs = require('fs');

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

1

Responding roughly. This <buffer ...> corresponds to binary data allocated in memory, memory this out of heap V8.

Buffer in the 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 is not scalable. It has specific methods for working with binary data. Their values, which represent the bytes in memory, they have a limit of 0 á 255 (2 8 - 1).

Reference: How to Use Buffers in Node.js

0

Buffer is your parsed file in hexadecimal format. You can take your answer and parse from simple form. Follow an example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.