Neto Braghetto
Neto Braghetto

Reputation: 1381

Why receiving an empty array?

Guys i am a begginer in nodejs... why at the end of my forEach my "filtered" array is empty ? and how to solve this problem ? Here is my code

var fs = require('fs');
module.exports.listByType = function(dirname, filter, callback) {
    try {
        var filtered = [];
        fs.readdir(dirname, function(e, list) {
            list.forEach(function(f) {
                if (f.split('.').pop() === filter) {
                    filtered.push(f);
                }
            });
        });
        callback(null,filtered);
    } catch (e) {
        callback(e);
    }
};

Upvotes: 0

Views: 202

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Because readdir is asynchronous, so your code calling the callback occurs before the array is filled. If the receiving code uses the array right away, it will be empty. (If that code waits on something else asynchronous rather than using the array right away, the results will be chaotic, the array may or may not have something in it by the time the receiving code uses it.)

You want to move your call to the callback inside the readdir callback:

var fs = require('fs');
module.exports.listByType = function(dirname, filter, callback) {
    try {
        var filtered = [];
        fs.readdir(dirname, function(e, list) {
            list.forEach(function(f) {
                if (f.split('.').pop() === filter) {
                    filtered.push(f);
                }
            });
            callback(null,filtered); // <=== Moved this line
        });
    } catch (e) {
        callback(e);
    }
};

You can also move the filtered variable into the callback:

var fs = require('fs');
module.exports.listByType = function(dirname, filter, callback) {
    try {
        fs.readdir(dirname, function(e, list) {
            var filtered = [];      // <=== Also moved this line
            list.forEach(function(f) {
                if (f.split('.').pop() === filter) {
                    filtered.push(f);
                }
            });
            callback(null,filtered); // <=== Moved this line
        });
    } catch (e) {
        callback(e);
    }
};

Upvotes: 1

Related Questions