Htlcs
Htlcs

Reputation: 555

return a final object from multiple callbacks javaScript

I am very new to JavaScript and Node.js. What I am trying to do is use Node's filestream to read a bunch of images and js files from two different directories. I have written a fileReader.js module for reading images and .js files like below

var fs = require('fs');

//module to read all the images from the images directory --> either .jpg or .png images and filter out the rest
function readImages()
{
    var imageArray = [];
    fs.readdir('../images',function(err,files)
    {       
        files.filter(function(file)
        {
            return ( (file.substr(-4) === '.png') || (file.substr(-4) === '.jpg') );
        }).forEach(function(file)
        {
            imageArray.push(file);
        });
        console.log(imageArray);
        return imageArray;
    });
    //or return here???
}

//module to read all the javascript files and filter out non js files
function readJSFiles()
{
    var jsArray = [];
    fs.readdir('../jsfiles',function(err,files)
    {       
        files.filter(function(file)
        {
            return ( (file.substr(-3) === '.js') );
        }).forEach(function(file)
        {
            jsArray.push(file);
        });

        console.log(jsArray);
        return jsArray;
    });
    // or return here???
}

exports.readImages = readImages;
exports.readJSFiles = readJSFiles;

Now I am trying to return two different array objects one for list of images and other for list of js files. I want to use these objects in my main.js file so I call them like below in my main.js

var filereader = require('./fileReader');

var images = filereader.readImages();
var jsfiles = filereader.readJSFiles();

But these array objects are empty in the main.js file. From what I understand, this has something to do with callbacks but how do I go about solving this problem??

Upvotes: 1

Views: 1774

Answers (1)

Liam Schauerman
Liam Schauerman

Reputation: 841

You don't want to set return values for these asynchronous functions. Instead, invoke a callback function once your fs method has completed.

function readImages(callback)
{
    var imageArray = [];
    fs.readdir('../images',function(err,files){       
        files.filter(function(file){
            return ( (file.substr(-4) === '.png') || (file.substr(-4) === '.jpg') );
        }).forEach(function(file){
            imageArray.push(file);
        });
        console.log(imageArray);

        //invoke the function from above
        callback(imageArray);
    });
}

You can write your readImages() function to accept a callback function. This callback function will set your images variable to point to the array of images.

//main.js
var filereader = require('./fileReader');
var images;

filereader.readImages(function(myImagesFromFs){
  images = myImagesFromFs;
});

Upvotes: 3

Related Questions