Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS: Asynchronous file read problems

NodeJS: Asynchronous file read problems

Problem

New to NodeJS.

Yes I know I could use a framework, but I want to get a good grok on it before delving into the myriad of fine fine tools that are out there.

my problem:

var img = fs.readFileSync(path);

the above works;

fs.readFile(path, function (err, data) 
        {
            if (err) throw err;
            console.log(data);
        });

the above doesn't work;

the input Path is : 'C:\NodeSite\chrome.jpg'

oh and working on Windows 7.

any help would be much appreciated.

Fixed Late night/morning programming, introduces errors that are hard to spot. The path was being set from two different places, and so the source path were different in both cases. Thankyou for your help. I am a complete numpty. :)

Problem courtesy of: WeNeedAnswers

Solution

If you are not setting an encoding when reading a file, you will get the binary content.

So for example, the following snippet will output the content of the test file using UTF-8 encoding. If you don't use an encoding, you will get an output like "" on your console (raw binary buffer).

var fs = require('fs');

var path = "C:\\tmp\\testfile.txt";
fs.readFile(path, 'utf8', function (err, data) {
  if (err) throw err;
  console.log(data);
});

Another issue (especially on windows-based OS's) can be the correct escaping of the target path. The above example shows how path's on Windows have to be escaped.

Solution courtesy of: schaermu

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS: Asynchronous file read problems

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×