0

Im new to nodeJs and I want to read file from the system, I was able to see the file content in the console but not in the browser and I

what am I missing here?

var myData = null;
    fs.readFile('C:\\Users\\jbt\\Desktop\\simplefile.txt', 'utf8', function (err,data) {
        if (err) {
            return console.log("the error is: " + err);
        }
        console.log(data);
        myData = data;
    });
    res.send(myData);

I try some other post in SO but nothing helps..

John Jerrby
  • 1,683
  • 7
  • 31
  • 68
  • This question is beginning to be posted too often... always the same answer : Javascript is _asynchronous_. Same question yesterday, please read my answer : http://stackoverflow.com/questions/30636547/how-to-set-retrieve-callback-in-mongoose-in-a-global-variable/30636635#30636635 – Jeremy Thille Jun 05 '15 at 09:40
  • @JeremyThille - Thanks but I dont understand how it helps me here... – John Jerrby Jun 05 '15 at 09:45
  • It's just exactly the same problem and the same answer. You're sending a variable that's not been filled because the process is _asynchronous_. It's almost the same code in both questions, except in your case it's readFile instead of a SQL query. – Jeremy Thille Jun 05 '15 at 09:50
  • Aside from the async issues, you're not showing us all of your code, because the code you're showing wouldn't result in the error you're getting. – robertklep Jun 05 '15 at 10:01
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Ben Fortune Jun 05 '15 at 10:34

3 Answers3

1

you are trying to send the response twice ie. res.send() is being called twice that is why once the response is sent you cannot resend it.

Aditya_Anand
  • 525
  • 7
  • 17
0

fs.ReadFile is async operation, you are sending response back and reading file in parallel. You should do it like this

    var myData = null;
    fs.readFile('C:\\Users\\jbt\\Desktop\\simplefile.txt', 'utf8', function (err,data) {
        if (err) {
            return console.log("the error is: " + err);
        }
        console.log(data);
        myData = data;
        res.send(myData);
    });

I would suggest you should read more about Node.js and async method paradigm.

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
0

Please post your error if you are getting any ?.Check the below answer.

var myData ;
    fs.readFile('C:\\Users\\jbt\\Desktop\\simplefile.txt', 'utf8', function (err,data) {
        if (err) {
            return console.log("the error is: " + err);
        }
        console.log(data);
        myData = data;
       res.end(myData);//If you are not using express
    });

I think it will help you.

rajat_474
  • 346
  • 1
  • 4
  • 15