Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encoding is ignored in fs.readFile

Tags:

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

like image 434
Micha Roon Avatar asked Apr 02 '13 19:04

Micha Roon


People also ask

What does the readFile () method require?

readFile() Method. Parameters: The method accept three parameters as mentioned above and described below: filename: It holds the name of the file to read or the entire path if stored at other location. encoding: It holds the encoding of file.

What Is syntax of readFile () method?

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. Syntax: fsPromises.readFile( path, options )

What does fs readFile?

fs. readFile() is an asynchronous and a very easy to use method for reading files of any type.

How do I get data from fs readFile?

var content; fs. readFile('./Index. html', function read(err, data) { if (err) { throw err; } content = data; }); console.


1 Answers

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:

  • v0.8.22
  • v0.6.21
like image 108
Jonathan Lonowski Avatar answered Oct 22 '22 10:10

Jonathan Lonowski