28

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

Micha Roon
  • 3,957
  • 2
  • 30
  • 48

2 Answers2

46

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:

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
9

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 );
});
Flexo
  • 87,323
  • 22
  • 191
  • 272
youssouf
  • 91
  • 1
  • 1
  • anyway fs not support some charsets like `ISO-8859-1` for this reason I've needle to use this answer http://stackoverflow.com/a/14551669/2979435 – deFreitas May 30 '16 at 01:16