0

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. :)

2
  • 3
    what doesn't work? The example you showed works. Commented Jan 19, 2012 at 6:15
  • The second piece of code produces an error saying , off the top of my head "string or buffer required." Commented Jan 19, 2012 at 12:57

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

java guys will just use this javascript asynchronous command as if in pure java , troublefreely :

var fs = require('fs');
var Contenu = fs.readFileSync( fILE_FULL_Name , 'utf8');
console.log( Contenu );

That should take care of small & big files.

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.