繁体   English   中英

Readline 'close' 事件在读取 txt 文件的第一行后触发

[英]Readline 'close' event firing after reading the first row of a txt file

我正在使用 Node.js 编写服务器代码,我需要使用 readline 模块从 txt 文件中读取行。 我遇到的问题是“关闭”事件在读取文件的第一行后触发,我哪里错了?

    rl.on('line', function (line) {
        var longest=true;

        nLines++;
        var words=line.split(" ");
        nWords += words.length;
        wordsPerLine[nLines] = words.length;
        for(len in wordsPerLine) if(len > words.length) longest=false;
        if(longest) longestLine=nLines;
        console.log("Line: ",nLines," - ",words.length," words, "," is the longest: ",longest);
        rl.close();
    }).on('close',function (line) {
        console.log("Counted: "+nWords+" words, longest line is number "+longestLine);
        res.write(getResponse(file, nLines,nWords, wordsPerLine,longestLine)); 
        res.end();
    });

您在事件处理程序中调用 rl.close。 它永远不会完成你的文件的过程。 您的 readline 将在行结束后调用 closed 事件。 按照这个例子:

(() => {
    var rl = require('readline').createInterface({
        input: require('fs').createReadStream('file.txt')
    });

    rl.on('line', function (line) {
      console.log(line)
    });

    rl.on('close', function (line) {
       console.log("close")
    });
})()

node.js 官方文档中阅读更多内容。

按照这些其他选项执行您尝试执行的相同操作: https ://geshan.com.np/blog/2021/10/nodejs-read-file-line-by-line/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM