Use variable out of cycle for NodeJS

0

I am trying to fill an array using the 'push' function within a for loop, but calling the array out of the loop is still empty.

They could help me understand how this part works.

app.get('/ReturnStatus', function(request, response) {
 var content = []
 fs.readdirSync(Folder).forEach(function(file) {
    fs.readFile(Folder+file, 'utf8', function(err, data) {
        if (!err) {
                parser.parseString(data, function (err, result) {
                    content.push(result)
            });
        }
    });
});
 response.json(content);
});
    
asked by Rasimus.84 19.10.2018 в 21:05
source

1 answer

3

What is happening here is simple, the program would be reading all the directories in a trabante way with the function readdirSync , but when sending to read each file individually with the function readFile is opening asyncronicas tasks, that does not wait to return the result. The solution to this problem would be to replace the call to readFile with its synchronous alternate readFileSync :

app.get('/ReturnStatus', function(request, response) {
    var content = []
     fs.readdirSync(Folder).forEach(function(file) {
        fs.readFileSync(Folder+file, 'utf8', function(err, data) {
            if (!err) {
                    parser.parseString(data, function (err, result) {
                        content.push(result)
                });
            }
        });
    });
    response.json(content);
});

NOTE: You did not specify where the parser object comes from, it takes a callback function, so it is very possible that it should also be replaced by a synchronous substitute.

    
answered by 19.10.2018 / 21:25
source