0

I have a file temp.js that contains text as below:

module.config = {
  key1 : 'value1',
  key2 : 'value2',
  key3 : ['abc','def']

}

I am reading the file as below:

fs.readFile('/temp.js', function(err,fileContents) {
   console.log(fileContents);
});

on the output I am getting values as below:

<Buffer 6d 6f .....
...>

What am i missing here ?

2
  • You're reading the hex contents of the file; it's being read as a binary rather than as a text string. Easy way to tell? In ASCII, all the lowercase letter range starts with 0x61, and the uppercase range starts with 0x41. Commented Jul 21, 2014 at 13:28
  • 6d 6f are the letters m and o. I'm guessing you want to evaluate the file as Javascript, which... really isn't what you're doing, here. Commented Jul 21, 2014 at 13:29

2 Answers 2

2

From the documentation for fs.readFile:

If no encoding is specified, then the raw buffer is returned.

Therefore, if you want a string passed to your callback, specify the encoding of the file. Example:

fs.readFile('/temp.js', {encoding: 'utf8'}, function(err, fileContents) {
   console.log(fileContents);
});
Sign up to request clarification or add additional context in comments.

Comments

0

The file is being read but as Buffer. To read it as string you've to tell fs the encoding.

Try this

require('fs').readFile('/temp.js','utf-8', function(err,fileContents) {
   console.log(fileContents);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.