Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is fs.readFile returning a buffer?

I have referred to this question already. That is, I don't believe my problem lies in a misunderstanding of async.

Here is the relevant part of my module.

var fs = require('fs');
var q = require('q');
var u = require('../utils/json');

var indexFile = './data/index.json';

function getIndex() {
    var def = q.defer(),
        promise = def.promise,
        obj;

    fs.readFile(indexFile, function(err,data) {
        if (err) {
            throw err;
            def.reject(err);
        }
        console.log('data', data);

        def.resolve(obj);
    });

    return promise;
}

When I log 'data', I'm getting a buffer (below), rather than the JSON content of that file.

<Buffer 5b 7b 22 68 65 6c 6c 6f 22 3a 22 77 6f 72 6c 64 22 7d 5d>

Any thoughts on why?

like image 475
Bryce Johnson Avatar asked Oct 09 '14 02:10

Bryce Johnson


People also ask

Does readFile return anything?

readFile. Returns the contents of the file named filename. If encoding is specified then this function returns a string. Otherwise it returns a buffer.

Why does readFileSync return buffer?

readFileSync returns a Buffer if encoding is not specified.

What is buffer in fs?

js buffers are objects that store arbitary binary data. The most common reason for running into buffers is reading files using Node. js: const fs = require('fs'); const buf = fs. readFileSync('./package.

What does the readFile () method require?

readFile() method is used to read the file. This method read the entire file into buffer. To load the fs module, we use require() method. It Asynchronously reads the entire contents of a file.


2 Answers

As per the Node.js API docs for 'fs' module, if the encoding option isn't passed, the read functions will return a buffer.

If you pass a value for encoding, it will return a string with that encoding:

fs.readFile('/etc/passwd', 'utf-8', callback)

like image 128
aarosil Avatar answered Sep 23 '22 15:09

aarosil


Try this... You need to include encoding

fs.readFile(indexFile,'utf8', function(err,data) {
    if (err) {
        throw err;
    }
    //Do something with data
    console.log(data);
});
like image 24
T M Avatar answered Sep 21 '22 15:09

T M