javascript - Node.js 应用程序中的阻塞功能

标签 javascript node.js multithreading asynchronous

我正在创建一个 Node.js 应用程序。它的功能之一是上传一个excel文件,然后读取它并将其内容保存在数据库中。问题是我是node.js的新手,我不理解非阻塞代码的概念,所以这个函数似乎阻塞了主线程,所以我需要一些帮助来解决这个问题。

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

parsing_file函数解析文件并将值作为对象存储到数组中,当数据库查询循环(负责将值插入数据库)开始时,问题就开始了,因为 Node.js 的主线程被阻塞,直到循环完成其工作。

最佳答案

使用 fs.readFile 从文件中读取数据,这是异步操作,使用 async.eachLimit 而不是 for 循环,这是非阻塞异步操作,而 for 循环 if 同步操作

 fs.readFile('./public/uploads/sample_file.xlsx', function (err, data) {
        if (err) {
            res.status(500).send(err);
        } else {
            var entries = parsing_file(req, res);                
            if (entries.length > 0) {
                async.eachLimit(entries, 10, function(entrie, callback){                      
                    model.insert_in_db(entrie, function(rows) {callback()});
                },function(err){
                      if( err ) {
                         // One of the iterations produced an error.
                         // All processing will now stop.
                         console.log('A file failed to process');
                      } else {
                          console.log('All files have been processed 
                          successfully');
                          return res.redirect('/admin');
                      }
               })                
        }           
  });

阅读https://caolan.github.io/async/docs.html#eachLimit异步文档了解更多详细信息。

关于javascript - Node.js 应用程序中的阻塞功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837980/

相关文章:

python - 'QThread : Destroyed while thread is still running' on quit

javascript - 仅当用户登录时运行 JavaScript 函数 - Django

javascript - 页面刷新后需要勾选复选框

sql-server - 如何使用 Sequelize 调用 MSSQL 存储过程?

Android:使用处理程序注册 SensorEventListener?

java - jstack 输出 - 获取 java Thread.getId 的 tid

javascript - 让谷歌地图填充高度

javascript - 在 WebGL 中渲染多个对象

node.js - gulpfile 只用 watch 运行一次

database - Firebase 设置方法不起作用