简体   繁体   中英

Node always returns empty array

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!?

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

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM