[javascript] 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$ 

This question is related to javascript file-io node.js

The answer is


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) {...});

It is returning a Buffer object.

If you want it in a string, you can convert it with data.toString():

var fs = require("fs");

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

Try:

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

Basically, you need to specify the encoding.


Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

data.toString('ascii', 0, data.length)

Asynchronously:

fs.readFile('test.txt', 'utf8', function (error, data) {
    if (error) throw error;
    console.log(data.toString());
});

This comes up high on Google, so I'd like to add some contextual information about the original question (emphasis mine):

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

Because files aren't always text

Even if you as the programmer know it: Node has no idea what's in the file you're trying to read. It could be a text file, but it could just as well be a ZIP archive or a JPG image — Node doesn't know.

Because reading text files is tricky

Even if Node knew it were to read a text file, it still would have no idea which character encoding is used (i.e. how the bytes in the file map to human-readable characters), because the character encoding itself is not stored in the file.

There are ways to guess the character encoding of text files with more or less confidence (that's what text editors do when opening a file), but you usually don't want your code to rely on guesses without your explicit instruction.

Buffers to the rescue!

So, because it does not and can not know all these details, Node just reads the file byte for byte, without assuming anything about its contents.

And that's what the returned buffer is: an unopinionated container for raw binary content. How this content should be interpreted is up to you as the developer.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`