Synchronous issue to save a file into GridFS - Node.JS/Express

I'm trying to save a profile photo from a social network as Facebook in my "fs.files" and "fs.chunks" as well, I can achieve this but the way I found to do it is not properly one.

My steps are:

  1. Make user logon on the Facebook using Passport;
  2. Saving the picture file on the disk (an internal application folder);
  3. Open and read the picture file and store it on the properly collections (files and chunks from Mongo).

The problem happens between steps 2 and 3, because saving a file on the disk in this case is not the best idea and a synchronous issue and latency happens when attempt to store it on the DB.

I had used setTimeout javascript function to make it happens. But it is so bad, I know. I wonder to know somehow a way to get some kind of file stream and store it directly on the GridFS or to make the the actual process more efficient:

The codes:

Get the picture from an URL and save it (disk step)

// processing image 'http://graph.facebook.com/' + user.uid + '/picture';
// facebook -> disk
var userProfilePhoto = user.provider + '_' + user.uid + '.png';

request(user.photoURL)
    .pipe(fs.createWriteStream(configApp.temp_files + userProfilePhoto));

Get the picture saved on the disk and store it on the GridFS

setTimeout(function() {
    mongoFile.saveFile(user, true, userProfilePhoto, mimeType.mime_png, 
        function(err) {
            if (!err) {
                user.save();
            }
        }
    );
}, 5000);

Unfortunately I had to use setTimeout to make it possible, without it the mongo just insert on "fs.files" and skip "fs.chunks" because the file is not ready yet - seems to be not saved yet.

I did it!

I replaced request plugin for http-get so when the file is ready I can store it in MongoDB.