javascript - Node.js 与 Express : Push to an empty Array returns an empty Array

标签 javascript node.js express asynchronous synchronous

我列出了 /home/myComputer/Desktop/Research 中所有目录中的所有文件,然后使用 if 语句过滤它们,以仅获取我想要读取和的 .txt 文件存储到数组中。一切正常,但将数据插入数组不起作用。当我通过控制台记录它们时,它们不返回任何值[]

我尝试了 Promise 和回调函数,但它们对我不起作用,因为我不知道如何正确实现它们。

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

    /* Define Arrays */
    var theFile = [];
    var theCategory = [];
    var theContent = [];

    var walk = function(dir, done) {
      var results = [];
      fs.readdir(dir, function(err, list) {
        if (err) return done(err);
        var i = 0;
        (function next() {
          var file = list[i++];
          if (!file) return done(null, results);
          file = dir + '/' + file;
          fs.stat(file, function(err, stat) {
            if (stat && stat.isDirectory()) {
              walk(file, function(err, res) {
                results = results.concat(res);
                next();
              });
            } else {
              results.push(file);
              next();
            }
          });
        })();
      });
    };


    //walk(process.env.HOME, function(err, results) {
    walk("/home/myComputer/Desktop/Research", function(err, results) {
      if (err) throw err;
      //console.log(results);

        results.map(function(val) {
            //Get the filename
            var fileName = val.match(/[^\/]+$/).join();
            //Get the category
            var category = val.substr(48).match(/[^\/]+/);

            if (fileName == 'written-speech.txt') {
                console.log('FOUND!: ' + fileName + ' Category: ' + category) //this works

                fs.readFile(val, 'utf8', function(err, contents) {
                    console.log(contents); // this works

                    theFile.push(fileName);
                    theCategory.push(category);
                    theContent.push(contents);
                });
            }
        })

    });

        console.log(theFile); // The problem: This returns an empty Array []
        console.log(theCategory); // The problem: This returns an empty Array []
        console.log(theContent); // The problem: This returns an empty Array []

});

我期望 console.log(theFile); console.log(theCategory);console.log(theContent); 返回数据推送到其中。

最佳答案

原因是 Javascript 中的许多回调都是异步的,这意味着 fs.readdirfs.readFile 都是异步的,它们的回调不会立即调用,而是会立即调用。稍后(请阅读 javascript 中的事件循环)。因此,目前,当您记录数组时,它们是空的,并且数据将稍后推送,例如在未来。为了避免这种情况,您可以使用同步方法(fs.readdirSync 和 fs.readFileSync),这种方法很丑陋,并且如果应用程序有很多其他异步操作,则可能会导致性能问题。如果您的情况只是一个读取一些数据的简单脚本,那么可能没问题。 另一种首选方法是使用 Promise 或某些库来管理回调,例如异步。如果您完全不熟悉这些概念,请阅读一些有关管理异步代码的文章,例如https://dev.to/mrm8488/from-callbacks-to-fspromises-to-handle-the-file-system-in-nodejs-56p2获得基本的了解并查看一些用例示例。

对于您当前的版本,没有简单的方法可以使其在不进行大量更改的情况下工作。最好重写它以使用我之前描述的概念。

关于javascript - Node.js 与 Express : Push to an empty Array returns an empty Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57646537/

相关文章:

绝对和相对 URL 的 javascript 正则表达式

javascript - Knockout.js:使用带有映射插件的嵌套可观察量

node.js - AWS Lambda 访问子文件夹中的模块被拒绝

node.js - React 浏览器兼容性低至 ie11

javascript - 如何在nodejs上的.env中设置变量

javascript - Mysql AES_ENCRYPT => 客户端 JavaScript Aes.Ctr.decrypt 问题

node.js - 类型错误 : Explicit type conversion not allowed from "int_const -1" to "uint256"

c++ - 如何从 Node 在 Heroku 上运行可执行文件,在本地工作

javascript - NodeJS Express,添加事务 ID

express - GET请求返回html而不是对象,返回的路由无法进入Heroku服务器