Micha Roon
Micha Roon

Reputation: 4009

encoding is ignored in fs.readFile

I am trying to read the contents of a properties file in node. this is my call:

fs.readFile("server/config.properties", {encoding: 'utf8'}, function(err, data ) {
   console.log( data );
});

The console prints a buffer:

<Buffer 74 69 74 69 20 3d 20 74 6f 74 6f 0a 74 61 74 61 20 3d 20 74 75 74 75>

when I replace the code with this:

fs.readFile("server/config.properties", function(err, data ) {
   console.log( data.toString('utf8') );
});

it works fine. But the node documentation says the String is converted to utf8 if the encoding is passed in the options

the output of node --version is v0.10.2

What am I missing here?

thank you for your support

Upvotes: 28

Views: 51599

Answers (2)

youssouf
youssouf

Reputation: 91

You should change {encoding: 'utf8'} to {encoding: 'utf-8'}, for example:

fs.readFile("server/config.properties", {encoding: 'utf-8'}, function(err, data ) {
console.log( data );
});

Upvotes: 9

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

Depending on the version of Node you're running, the argument may be just the encoding:

fs.readFile("server/config.properties", 'utf8', function(err, data ) {
   console.log( data );
});

The 2nd argument changed to options with v0.10:

  • FS readFile(), writeFile(), appendFile() and their Sync counterparts now take an options object (but the old API, an encoding string, is still supported)

For former documentation:

Upvotes: 46

Related Questions