【问题标题】:Variables reset automatically to their initial values in NodeJS script?变量在 NodeJS 脚本中自动重置为其初始值?
【发布时间】:2016-06-15 20:48:30
【问题描述】:

在我开始拔头发之前,我想我应该先寻求帮助:

我正在尝试从文件中读取数据(逐行)并计算每行中前两个字符出现的频率。结果应该被写入文本文件。

如果一行以** 开头,则增加一个计数器 (recordCount) 并打印到控制台。它打印越来越多的数字到控制台。但是,如果我访问 lineReader.on() 块下方的这个或另一个变量,它们都有它们的初始值。这怎么可能?

"use strict";

// ...

function processFile(filePath, outFile) {
    let inFile = fs.createReadStream(filePath).pipe(new bomstrip());

    let lineReader = readline.createInterface({
        input: inFile
    });
    let tagCounts = {};
    let recordCount = 0;

    lineReader.on("line", function(line) {
        let tag = line.slice(0, 2);
        tag.trim();
        if (!tag) {
            return;
        }
        else if (tag == "**") {
            recordCount++;
            console.log(recordCount); // prints increasing numbers to console
        } else {
            let val = tagCounts[tag];
            if (val === undefined) {
                tagCounts[tag] = 1;
            } else {
                tagCounts[tag]++;
            }
        }
    });

    console.log(recordCount); // prints 0, but why?!

   // ...
}

我在 Windows 8.1 64 位上使用 Node v5.7.0。我也尝试了var 而不是let,但结果相同。

【问题讨论】:

  • 这是因为lineReader.on() 是一个异步事件处理程序,一行被读取时触发
  • 好点...这是否意味着我不能使用 readline,因为没有办法同步读取行?或者我还能如何将结果传递给外部?
  • 你根本无法将结果传递给外部,你必须处理异步,看这个 -> stackoverflow.com/questions/14220321/…

标签: javascript node.js variables scope


【解决方案1】:

您仍然可以使用您的代码,但需要进行一些调整。如果要打印总计数,则必须等到整个文件读取完成。您可以通过收听the 'close' event 来做到这一点。

这段代码可能就是你想要的:

"use strict";

// ...

function processFile(filePath, outFile) {
    let inFile = fs.createReadStream(filePath).pipe(new bomstrip());

    let lineReader = readline.createInterface({
        input: inFile
    });
    let tagCounts = {};
    let recordCount = 0;

    lineReader.on("line", function(line) {
        let tag = line.slice(0, 2);
        tag.trim();
        if (!tag) {
            return;
        } else if (tag == "**") {
            recordCount++;
            console.log(recordCount); // prints increasing numbers to console
        } else {
            let val = tagCounts[tag];
            if (val === undefined) {
                tagCounts[tag] = 1;
            } else {
                tagCounts[tag]++;
            }
        }
    });

    lineReader.on("close", function() {
        console.log(recordCount); // prints 0, but why?!
    });

    // ...
}

【讨论】:

  • 尤里卡! close-event 函数中的所有内容都在读取内容后运行,因此可以访问 post 状态。这么简单的修改就解决了,非常感谢!
  • 太棒了,很高兴听到这个消息:)
猜你喜欢
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2011-02-18
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多