Thursday, 16 March 2017

Blocking function in nodejs application

I am creating a node js application one of its function is to upload an excel file , then read it and save its content in the database the problem that I am new to node js and I don't understand the concept of non blocking code so it seems this function block the main thread so I need consultancy to solve this issue.

`

app.post('/admin/upload_file', function(req, res) {
    var sampleFile;
    if (!req.files) {
        res.send('No files were uploaded.');
        console.log('No files were uploaded.');
        return;
    }
    sampleFile = req.files.sampleFile;
    var fileArray = sampleFile.name.split('.');
    var extension = fileArray[fileArray.length - 1];
    if (extension == "xlsx") {
        sampleFile.mv('./public/uploads/sample_file.xlsx', function(err) {
            if (err) {
                res.status(500).send(err);
            } else {
                var entries = parsing_file(req, res);
                if (entries.length > 0) {
                    for (var i = 0; i < entries.length; i++) {
                        // this loop on database queries block the main thread
                        model.insert_in_db(entries[0], function(rows) {});
                    }
                }
                res.redirect('/admin');
            }
        });
    } else {
        res.redirect('/admin');
  }
});

`

The parsing_file function parse the file and store the values as objects into an array, the problem starts when the loop on the database query (which is responsible of inserting the values in the db) starts as the main thread of node js became blocked until the loop done it's work



via Karim

No comments:

Post a Comment