【问题标题】:How to push lines from Line Reader to an array?如何将行从 Line Reader 推送到数组?
【发布时间】:2019-06-23 13:01:18
【问题描述】:

我被这个问题难住了。我正在尝试将包含文本文件每一行的子字符串的对象推送到 fs linereader 范围之外的数组。我几乎肯定我的数组在正确的范围内,但我的数组总是空的。

代码运行没有任何错误,我什至可以从文本文件中打印出每一行都没问题。

我正在尝试使用 Node 从文本日志文件中获取行并将每行的各个部分推送到数据库。

var watcher = chokidar.watch("MyFolder", {ignored: /^\./, persistent: true});
watcher
  .on('add', function(path) {
    var myArray = [];
    console.log('File', path, 'has been added');
    var lineReader = require('readline').createInterface({
      input: require('fs').createReadStream(path)
    });
    lineReader.on('line', function (l) {
      l.toString();   
      myArray.push({
        "date" : l.substring(25,35),
        "time" : l.substring(35,46)
       });
    });
    console.log(myArray); //Always empty
  })
  .on('change', function(path) {console.log('File', path, 'has been changed');})
  .on('unlink', function(path) {console.log('File', path, 'has been removed');})
  .on('error', function(error) {console.log('Error happened', error);});

我希望控制台向我显示数组,但它始终是空的。

【问题讨论】:

  • 当然是空的,记住lineReader.on('line'注册了一个回调函数,将在未来的事件循环中执行,而你的console.log在当前的事件循环中执行。 . 换句话说:你刚刚注册了回调函数,还没有执行......
  • 啊!谢谢,我没有在回调中考虑到这一点。是他们异步运行对吗?我想我正确地使用了这个词。我正在玩弄它,但我可以将它包装在 Promise 中吗?

标签: arrays node.js request fs


【解决方案1】:

你得到空数组的原因是因为 ReadLine 在IO event queue 中添加了回调,它将在当前执行脚本完成后执行。所以它看起来像定义数组并在下一行打印它。为了打印数组中的所有值,您只需在 lineReader ReadLine object 上为 close 事件添加一个侦听器。

下面是带有close事件的更新代码。

var watcher = chokidar.watch("MyFolder", {ignored: /^\./, persistent: true});
watcher
  .on('add', function(path) {
    var myArray = [];
    console.log('File', path, 'has been added');
    var lineReader = require('readline').createInterface({
      input: require('fs').createReadStream(path)
    });
    lineReader.on('line', function (l) {
      l.toString();   
      myArray.push({
        "date" : l.substring(25,35),
        "time" : l.substring(35,46)
       });
    });

    lineReader.on('close', function () {
      console.log(myArray);
    })

  })
  .on('change', function(path) {console.log('File', path, 'has been changed');})
  .on('unlink', function(path) {console.log('File', path, 'has been removed');})
  .on('error', function(error) {console.log('Error happened', error);});

【讨论】:

  • 啊,我想我需要一个 Promise 什么的。显然,我想多了。谢谢!
猜你喜欢
  • 2016-01-13
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多