比较两个文本文件 - 并将差异保存到新文件

Comparing two text files - and save difference to new file

我目前正在努力解决这个问题 - 所以情况是:

1. 从 FTP

下载 textFile1

2. 从 FTP

下载 textFile2

3.从PC本地文件读取数据并比较textFile1&2

4. 仅将差异(如整行)保存到文本文件 3

我试过对它进行 fs.readFile - 并比较 fileDiff (npm diff);但是我有点不确定如何处理,所以它只会将 1 和 2 之间的实际差异保存到第三个文本文件中。

将其视为 "compare & save"

希望有人对如何实现这个有任何想法,它有点难以解释。


//更新

代码片段(或看下面):https://jsfiddle.net/menix/py3eqnfL/

const ServerLog = "ServerDM/TheIsle/Saved/Logs/TheIsle.log";
const LocalSaveOld = "TheIsleData/TheIsle.log";
const LocalSaveNew = "TheIsleData/TheIsleNew.log";

async function example() {
    const client = new ftp.Client();
    client.ftp.verbose = true;

    try {
        await client.access({
            host: config.ftpHost,
            port: config.ftpPort,
            user: config.ftpUser,
            password: config.ftpPassword,
            secure: config.ftpSecure,
        });
        await client.downloadTo(LocalSaveOld, ServerLog);

        if (fs.existsSync(LocalSaveOld)) {
            fs.readFile(LocalSaveOld, function (err, data1) {
                console.log(data1);
                fs.readFile(LocalSaveNew, function (err, data2) {
                    console.log(data2);
                    var difference = fileDiff.diffLines(data1, data2);
                    console.log(difference);
                });
            });

            await fs.rename(LocalSaveOld, LocalSaveNew, function (err) {
                console.log("old was copied to new");
                if (err) console.log("ERROR: " + err);
            });
        }
    } catch (error) {
        console.log("FTP ERROR");
        client.close();
    }
}

这是我目前玩过的代码,很可能需要重新编码。

我的想法是首先通过 FTP 下载 ServerLog 文件到 PC(它保存为 LocalSaveOld pc) - 然后它应该在 5 分钟后再次重新下载 ServerLog,将其保存为 LocalSaveNew

然后我想比较 LocalSaveOld 和 LocalSaveNew - 并将 5 分钟内的 "new data" 保存到第三个文件(这就是我真正迷失的地方)

我想出了如何从 FTP 下载 ServerLog,将其保存为 LocalSaveOld。

我想出了如何将 LocalSaveOld 重命名为 LocalSaveNew

A Friend here has a working Python example; but obviously mine is done in Javascript - I wanna achieve same result

const string1 = fs.readFileSync(LocalSaveOld, { encoding: "utf8" });
const string2 = fs.readFileSync(LocalSaveNew, { encoding: "utf8" });
const diff = (diffMe, diffBy) => diffMe.split(diffBy).join("");
const finalString = diff(string2, string1);
fs.writeFile("./TheIsleData/diff.log", finalString, function (err) {
    if (err) return console.log(err);
    console.log("written");

是比较的答案 - 我现在已经完全正常工作了!