Why does fs.readFile return a buffer?

I already mentioned this question . That is, I do not believe that my problem is a lack of understanding of asynchrony.

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 get a buffer (below), not the JSON content of this 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?

+4
source share
3 answers

According to the Node.js API docs for the 'fs' module , if the option is encodingnot passed, Functions readreturn a buffer.

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

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

+8
source

...

fs.readFile(indexFile,'utf8', function(err,data) {
    if (err) {
        throw err;
    }
    //Do something with data
    console.log(data);
});
+1

As indicated earlier, the fs module requires the encoding parameter to be the second parameter.

Also, if you are sure that your file contains utf-8, you can use;

fs.readFile(indexFile, function(err,data) {
    if (err) {
        return def.reject(err);
    }

    console.log('data', data.toString());

    def.resolve(obj);
});
+1
source

All Articles