1

I have a route method to return a list of filenames in a http response.

The data structure I am using for the response is eventually populated, albeit after the response is returned, meaning I get an empty and useless response.

I can see the datastructure is populated in the end, as the output the contents to the log show.

Code:

app.get('/hello',function(req,res){

    var paths = {};

    fs.readdir('./uploads', function(err, items) {
    console.log(items);

    for (var i=0; i<items.length; i++) {
        paths[i] = items[i];
        console.log(items[i]);
    }
    });

    res.json(this,paths);
});
1
  • Do you mean that the issue is that res.json(this.paths) returns an empty JSON response? Commented Jun 26, 2017 at 5:41

2 Answers 2

2

You should return response after reading the file directory inside the callback.

Below is the code snippet for the same:

app.get('/hello',function(req,res){
    var paths = {};
    fs.readdir('./uploads', function(err, items) {
       console.log(items);
       for (var i=0; i<items.length; i++) {
          paths[i] = items[i];
          console.log(items[i]);
       }
       res.json(paths);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Just move the res.json() call inside the callback, after the for loop.

EDIT1:

app.get('/hello', function (req, res) {

    var paths = [];

    fs.readdir('./uploads', function (err, items) {

        console.log(items);

        for (var i=0; i<items.length; i++) {
            paths.push(items[i]);
            console.log(items[i]);
        }

        res.json(paths);
    });
});

1 Comment

Also, if the paths object is going to have numeric keys, then might as well make it an array. In which case, you don't have to use the for loop to populate the array, unless you have other operations to perform on each item.

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.