call two file from another with node js

Problem

I have a file called node.js:

var net = require('net');

var crypto = require('crypto');

//sjcl
var sjcl = require('./sjcl');

//retrive fb profile
var loadFb = require('./loadFb.js');
var loadFeed = require('./loadFeed.js');

//read json user file
var fs = require('fs');
var text = fs.readFileSync(__dirname + '/users','utf8');

var HOST = 'localhost';
var PORT = 7000;

net.createServer(function(sock) {

    // We have a connection - a socket object
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {

        console.log('User request profile of: ' + data);
        //var date = (data.toString()).split("***");
        //var from = date[1];

        loadFb(extendetPath, function(pageData) 
        {

          loadFeed(extendetPath2, function(pageData2) 
          {

            var fs = require('fs');
            var profileText = fs.readFileSync('/tmp/profile','utf8');
            console.log(profileText);
            sock.write(profileText);


          });

        });
    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT);

console.log('Server listening on ' + HOST +':'+ PORT);

function returnKeyFromUser(id)
{
  //text
  var trovata = false;
  var dati = JSON.parse(text);
  for(var i=0; i<dati.friendlist.friend.length && trovata==false; i++)
  {
    var user = (dati.friendlist.friend[i].username).replace("\n","");
    var userID = (id).replace("\n","");
    if(user==userID)
    {
      trovata=true;
      return ((dati.friendlist.friend[i].publicKey).toString()).replace("\n","");
    }
  }
  if(trovata==false)
    return null;
}

There is a small http server that receives a facebook username and what he have to do is retrieve 2 page:

a graphapi with the profile information, and a graphapi with the feed informations of a facebook profile I copy the other two files:

var https = require('https');

module.exports = function(path, callback) {
  var options = {
    host: 'graph.facebook.com',
    port: 443,
    path: (path.toString()).replace("\n",""),
    method: 'GET'
  };

  var req = https.get(options, function(res) {

    var pageData = "";

if((path.toString()).indexOf("/")==0 && (path.toString()).indexOf("/GET /`HTTP/")!=0) 
//for load only (I hope facebook profile)

    {

      console.log(options);

      res.setEncoding('utf8');

      res.on('data', function (chunk) {
        pageData += chunk;
      });

      res.on('end', function()
      {       

          var fs = require('fs');
          fs.writeFile("/tmp/profile", pageData, function(err) {
          if(err) {
              console.log(err);
          } else {
              console.log("The file was saved!");
          }
         });

        //callback(pageData);
        return;

      });
    }
  });
};

3° file

var https = require('https');

module.exports = function(path, callback) {
  var options = {
    host: 'graph.facebook.com',
    port: 443,
    path: (path.toString()).replace("\n",""),
    method: 'GET'
  };

  var req = https.get(options, function(res) {

    var pageData = "";

    if((path.toString()).indexOf("/")==0 && (path.toString()).indexOf("/GET / HTTP/")!=0) //for load only (I hope facebook profile)
    {

      console.log(options);

      res.setEncoding('utf8');

      res.on('data', function (chunk) {
        pageData += chunk;
      });

      res.on('end', function()
      {       

          var fs = require('fs');
          fs.appendFile('/tmp/profile', "***"+pageData, function (err) {
            if (err) throw err;
            console.log('It\'s saved!');

          });
          callback(pageData);
      });
    }
  });
};

I don't know If there is a way to call the two file in the first file node.js but what I done is this: (to call from node.js the fist file, and from the second file call the third) in node.js file I call the first file loadFb.js with this command:

loadFb(extendetPath, function(pageData) 
{

This call saves a file on my tmp profile directory and inside I call the other file loadFeed that appends some text.

After that I have to send the entire information to the client but I have a mistake. In order the nodejs correctly call loadFb and he write tmp - profile, than he call loadFeed but before appending the information the node call back to the client only the half of informations that I need. I'm not a good nodejs programmer, this is a work for my thesis. Can someone help me?

Problem courtesy of: Dario Vettore

Solution

Let's look at the following code:

  res.on('end', function()
  {       

      var fs = require('fs');
      fs.appendFile('/tmp/profile', "***"+pageData, function (err) {
        if (err) throw err;
        console.log('It\'s saved!');

      });
      callback(pageData);
  });

What it does it runs the asynchronous method appendFile and immediately after that calls callback. So when the code in the callback is executed, the file is not updated yet. You need to move the callback(pageData); to the appendFile's callback. And you need to review you code keeping this in mind because I see that the same fix should be made in another file so maybe there are some similar places as well.

Solution courtesy of: AlexAtNet

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.