首页 > 解决方案 > line-reader 逐行读取文件 - nodejs

问题描述

我正在尝试使用 line-reader 模块逐行读取一些文件(001.txt 到 654.txt)。当我执行我的代码时,它只适用于几个文件,其余的我只得到一行。例如,我只得到 002.txt 的第一行。附上该文件的图像以供参考,代码如下。

在此处输入图像描述

const lineReader = require("line-reader");
const f = path.join(__dirname + file);  
lineReaderParam.open(f, { bufferSize: 1024 }, (error, reader) => {
// reader.nextLine((error, line) => {
//   console.log("line 233", line);
//   songLineSections.title = line;
// });

if (reader.hasNextLine()) {
  while (reader.hasNextLine()) {
    reader.nextLine((err, line) => {
      // if (line === "Choeur") {
      //   section = { num: "", text: [] };
      //   section.choeur = line;
      // } else

      if (line === "Refrain") {
        section = { num: "", text: [] };
        section.refrain = line;

        //songLineSections.push(section);
      } else if (line === "") {
        //section = { num: "", text: [] };
        songLineSections.push(section);
        if (section.num === sectionNum) {
          section = { num: "", text: [] };
          if (songLineSections.length !== 0) {
            songsList.push(songLineSections);
          }
        } else {
          if (line === "") {
            section = { num: "", text: [] };
          }
        }
      } else {
        if (isNaN(line)) {
          section.text.push(line);
          songsList.push(songLineSections);
        } else {
          if (sectionNum !== line) {
            section.num = line;
            sectionNum = line;
          }
        }
      }
    });
  }
} else {
  reader.close(error => {
    console.log(error);
  });
}

songLineSections.push(section);
console.log("line 80", songLineSections);
event.reply("songNumberReply", songLineSections);

return songLineSections;

});

标签: node.jsfileline-by-line

解决方案


推荐阅读