【问题标题】:How to check a line of a file is present in the file in Javascript?如何检查文件中的一行是否存在于 Javascript 中的文件中?
【发布时间】:2021-10-23 20:45:26
【问题描述】:

我是 javascript 新手,我想检查一个文件的行是否存在于另一个文件中。我有以下代码:

async getReadLiner(filename) {
    const fileStream = fs.createReadStream(filename);
    const rl = readline.createInterface({
      input: fileStream,
    });
    return rl;
}

有没有可能做类似的事情

checkLines() {
    const file1 = await this.getReadLiner(filename1);
    const file2 = await this.getReadLiner(filename2);
    for await (const line of file1) {
      for await (const file2Line of file2) { 
            if (file2Line == line) // It's not executing this line at all.
                return true;
        }
    }
    return false
}

知道为什么这条线(if (file2Line == line) 没有执行吗?

提前致谢。

【问题讨论】:

  • readLines.indexOf("helo 123") != -1
  • @mplungjan - 仅当您将整个文件作为大数组读取时。 readline 模块可以避免这种情况,有利于保持流的概念。

标签: javascript node.js file stream readline


【解决方案1】:

有没有可能做类似的事情

是的,readline 模块的文档中有一个example of that,如下所示:

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  // Note: we use the crlfDelay option to recognize all instances of CR LF
  // ('\r\n') in input.txt as a single line break.

  for await (const line of rl) {
    // Each line in input.txt will be successively available here as `line`.
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();

调整循环:

const targetLine = "helo 123";
for await (const line of getReadLiner(/*...*/)) {
    if (line === targetLine) { // Or line.includes(targetLine) for a substring match
        // Found it
        break;
    }
}

【讨论】:

  • 但是如果 targetLine 来自另一个文件,它不会等待。像这样pastebin.com/iZ9iptWQ
  • @lakshmiravalirimmalapudi - 我不知道你的意思。该问题显示line 是一个常量(我在上面的代码中将其重命名为targetLine,因为linefor-await-of 控制变量的好名字)。什么是“不等待”? (for-await-of 肯定会等待流产生一行。)关于从另一个文件中获取您要查找的行的问题中没有任何内容。
  • 编辑了问题。寻找这样的东西pastebin.com/iZ9iptWQ
猜你喜欢
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2014-08-11
  • 1970-01-01
  • 2020-06-25
  • 2013-02-12
相关资源
最近更新 更多