3

I have the following Get request in server...

var imageFiles = [];
var dir = 'public/img/';
fs.readdir(dir, function(err, files){
    if (err) return console.error(err);
    files.forEach(function(file) {
            file = dir + file;
            imageFiles.push(file)
    });
});
res.send(imageFiles);
res.end();

imageFiles always returns to angular as an empty array. If I console.log(imageFiles) before the response it is empty as well. However, if I console.log(files) they are all there. What am I doing wrong!?

2
  • 1
    You are sending the response before the directory was traversed. readdir is asynchronous. Send the response inside the callback. Commented Mar 28, 2014 at 0:34
  • 1
    If you're going to use NodeJS, you're really going to need to spend some time learning about async programming. Commented Mar 28, 2014 at 0:34

2 Answers 2

0

fs.readdir is an async function. It completes in the callback function passing files.

So, when you do res.send, images files is empty.

var imageFiles = [];
...
fs.readdir(dir, function(err, files){
    // files is populated here after readdir returns.
});

// this line executes before readdir returns
res.send(imageFiles);

You need to do something like:

var imageFiles = [];
...
fs.readdir(dir, function(err, files){
    ...
    res.send(imageFiles);
    res.end();
});

Welcome to async programming :)

Checkout async.js. It helps untangle callback hell:

http://www.sebastianseilund.com/nodejs-async-in-practice

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! I knew it was async and feel stupid for not thinking of that... I'll mark this as the answer as soon as I can.
np - takes some getting used to.
0

Since Array.prototype.forEach is blocking, you can just call your other methods after the foreEach statement. ;

fs.readdir(dir, function(err, files){
    if (err) return console.error(err);
    files.forEach(function(file) {
            file = dir + file;
            imageFiles.push(file)
    });
    res.send(imageFiles);
    res.end();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.