【已解决】如何一行一行地并按顺序地读取两个文件?我用readline写的代码有问题,不知道为什么?
发布于 6 个月前 作者 shizengzhou 594 次浏览 来自 问答
const readline = require('readline');
const fs = require('fs');

function main() {
  const rl1 = readline.createInterface({
    input: fs.createReadStream(process.argv[2])
  });

  const rl2 = readline.createInterface({
    input: fs.createReadStream(process.argv[3])
  });

  const flag = process.argv[4];

  let whitelist = [];
  const tlist = [];
  rl1.on('line', line => {
    whitelist.push(Number(line));
  }).on('close', () => {
    whitelist = whitelist.sort((a, b) => a - b);
    rl2.on('line', line => {
      const key = Number(line);
      tlist.push(key);
      if (flag === '+') {
        if (binarySearch(key, whitelist) < 0) {
          // console.log(key);
        }
      } else if (flag === '-') {
        if (binarySearch(key, whitelist) > -1) {
          // console.log(key);
        }
      }
    }).on('close', () => {
      console.log(tlist.length);
    });
  });
}

main();

以上代码,当第二个参数是一个小文件(18行)时,tlist是个空的数组,当第二个参数是一个大文件(1000万行)时,tlist的长度却是9220850

回到顶部