DemCodeLines DemCodeLines - 3 months ago 17
Javascript Question

Values are not getting inserted into an array

I have a NodeJS app, where I am using ExcelJS in one of the routes (powered by Express). In the following snippet, a simple loop is supposed to read rows from the Excel file, then insert them into the array. However, they don't seem to be inserting.

router.get('/work', function(req, res, next) {
var posts = [];
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(file).then(function() {
var worksheet = workbook.getWorksheet(1);
worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
console.log(JSON.stringify(row.values));
posts.push(JSON.stringify(row.values));
});
});
res.json(posts);
});


That
console.log
line works just fine, as I am able to see the values in the console as they are logged. However, the values just don't get inserted into the
posts
array for some reason. Any one know why?

Answer

Since this operation is asynchronous, you need to send your array back after you have completed reading your CSV:

router.get('/work', function(req, res, next) {
    var posts = [];
    var workbook = new Excel.Workbook();
    workbook.xlsx.readFile(file).then(function() {
        var worksheet = workbook.getWorksheet(1);
        worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
            console.log(JSON.stringify(row.values));
            posts.push(JSON.stringify(row.values));
        });
        res.json(posts); // moved within the callback to `then`
    });
});

Before, you were immediately terminating the request with your empty array, before the promise returned by readFile resolved and allowed you to fill it with the values from your CSV.

Comments