gpt4 book ai didi

javascript - 如何读取 Node 中的两个文件并检查两个文件中是否存在单词

转载 作者:行者123 更新时间:2023-12-02 23:44:06 25 4
gpt4 key购买 nike

我正在尝试 Node 中的新事物,所以这里我想读取两个文件并检查文件中的所有单词是否相同。

示例:两个相似的文件,其中一个文件添加了一些额外的单词。

因此,在检查两个文件后,如果一个文件中的单词在另一个文件中不存在,则应该打印出这些单词

这是我到目前为止所尝试过的,但这似乎没有按预期工作,而且不是正确的方法

let newData = [];
let oldData = [];

(async () => {
await new Promise(resolve => {
fs.readFile(
pathname.join(__dirname, "public", "hello.txt"),
(err, data) => {
const wordsInFile = data.toString().toLowerCase();
// Here we should split string by some delimiter for further words processing. Assume, that your file looks like this "word1 word2". We'll use space delimiter.
newData = wordsInFile.split(" ");
resolve();
}
);
});

// here is the same code for the second file. Or you can move code to another function.
await new Promise(resolve => {
fs.readFile(pathname.join(__dirname, "public", "test.txt"), (err, data) => {
const wordsInFile = data.toString().toLowerCase();
// Here we should split string by some delimiter for further words processing. Assume, that your file looks like this "word1 word2". We'll use space delimiter.
newData = wordsInFile.split(" ");
resolve();
});
});
// And now we can use Set from ES6, to find intersection/difference etc.
const wordsNotInFileAndNotInFileTwo = new Set(
[...newData].filter(x => !oldData.has(x))
);
console.log(wordsNotInFileAndNotInFileTwo);

// But you can simple iterate two arrays to achieve your goal.
})();

如有任何帮助,我们将不胜感激

最佳答案

嵌套readFile:

fs.readFile(pathname.join(__dirname, "public", "hello.txt"), (err, data) => {
newData = data.toString().toLowerCase();
fs.readFile(pathname.join(__dirname, "public", "test.txt"), (err, data) => {
oldData = data.toString().toLowerCase();
if (newData === oldData) {
console.log("Same");
} else {
console.log("Not Same");
const a = newData.split(' ')
const b = oldData.split(' ')

const result = a.filter(w => !oldData.includes(w));
console.log(result.join(' '));
}
});
});

这样,内部函数中的回调就可以访问外部函数中设置的变量。

关于javascript - 如何读取 Node 中的两个文件并检查两个文件中是否存在单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55934149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com