首页 > 解决方案 > 如何使用 JAVASCRIPT 在文本文件中逐行执行字符串比较

问题描述

  1. 我需要将数据保存到文本文件。2)然后对文本文件中的每一行进行比较。
  2. 如果文件报告中存在单词行到目前为止,我能够阅读内容并在控制台上显示但我不知道如何进行比较。

示例:假设我第一次运行我的代码并保存在文本文件中

例如=我的脚本第一次运行时它在fileLoc中保存的数据{a,b,c} 我的意图当脚本下次运行时,如果fileLoc中存在相同的数据“{a,b,c}。我想报告此行。

我希望能够捕捉到这些比赛。

注意fileLoc永远不会改变,我的脚本每次都将数据保存在同一个文件中=>“rawDeal.txt”并带有时间戳,但我的要求是寻找方法来执行每行的某种字符串caparison。***** 这是我必须阅读文件中已有内容的代码,非常感谢任何方向。

NB==>>我每次保存新数据时都使用 fs.appendFile 添加到文件中。所以理想情况下,新添加的数据将位于底部,但我想检查上面的任何一行是否已经存在任何数据。

//*****     create fs package
 fs = require('fs');
 readline = require('readline');
//const fs = require('fs');
//******     fileLoc to save info
 fileLoc ="C:/rawDeal.txt"

  //*********   ('\r\n') in input.txt as a single line break.
  require('fs').readFileSync(fileLoc , 'utf-8').split(/\r?\n/).forEach(function(line){
  console.log(line);

标签: javascript

解决方案


您只想逐行比较 2 个文件。检查底部的编辑

// file1.txt
apple
mangoes
orange

//file2.txt
apple
mangoes
orange

//noMatchFile.txt
apples
bananas
oranges
// index.js
const fs = require("fs")
const { assert } = require("console") // for testing
const file1Location = "./file1.txt"
const file2Location = "./file2.txt"
const file3Location = "./noMatchFile.txt"

function CheckFiles(file1Location, file2Location) {
    const file1Lines = fs.readFileSync(file1Location, 'utf-8').split(/\r?\n/)
    const file2Lines = fs.readFileSync(file2Location, 'utf-8').split(/\r?\n/)
    // after these two readFile() functions, we have all the data we need

    for(let lineIndex in file1Lines) {
        if(file1Lines[lineIndex] !== file2Lines[lineIndex]) return false
    }
    return true
}

// Let's test ourselves
function main() {
    assert(CheckFiles(file1Location, file2Location) === true, 'expected file1 and file2 to match')
    assert(CheckFiles(file1Location, file3Location) === false, 'expected file1 and file3 not to match')
}

main()

将解决方案复制到您的计算机并运行它。assert()如果条件不满足,s 会抱怨


编辑:在评论中澄清您尝试做的事情后,解决方案有点不同。

您有一个记录数据的文件,并且每个更改都记录为一个新行。然后你应该逐行分割文件,并逐行比较。如果有任何更改,该函数将返回 false:

function CheckLines(file) {
    const fileLines = fs.readFileSync(file, 'utf-8').split(/\r?\n/)
    for(let index = 0; index < fileLines.length - 1; index++){
        if(fileLines[index] !== fileLines[index+1]) return false
    }
    return true
}

推荐阅读