Reputation: 3273
How can I read two file using fs and have both result available in a way , where I can compare them. I looked at this but its slightly different and I couldnt find a way to do what I need.
I can call the diffChars
from callback, but how to do with two callback functions?
fs.readFile('/abc1.txt', function (err, data1) {
console.log(data1);
});
fs.readFile('/abc1.txt', function (err, data2) {
console.log(data2);
});
later I want to do like this
var fileDiff = require("diff");
var difference = fileDiff.diffChars(data1,data2);
cnsole.log(difference);
note: I am restrictive on libraries I can use because of npm proxy repository
Upvotes: 1
Views: 3073
Reputation: 2358
Node uses asynchronous style of coding. So when you are reading file one the 2nd file is also being read and also the next code is being executed. Thus you can use promises or callbacks. Here is one solution
fs.readFile('/abc1.txt', function (err, data1) {
console.log(data1);
fs.readFile('/abc1.txt', function (err, data2) {
console.log(data2);
var fileDiff = require("diff");
var difference = fileDiff.diffChars(data1,data2);
console.log(difference);
});
});
or use promises like
var data;
fs.readFile('/abc1.txt')
.then((data1)=>{
data = data1;
return(fs.readFile('/abc1.txt'))
})
.then((data2)=>{
var difference = fileDiff.diffChars(data1,data2);
return(difference)
})
/* do what ever you want here*/
.catch((err)=>{throw err;})
Upvotes: 0
Reputation: 3682
You don't need the callback functions. You could use fs.readFileSync()
.
EDIT However, fs.readFileSync()
is blocking and the next line will only be executed once the function returns.
If you insist on using callbacks:
fs.readFile("abc123.txt", (error1, data1) => {
if (error1) {
return;
}
fs.readFile("abc456.txt", (error2, data2) => {
if (error2) {
return;
}
console.log(data1 === data2);
});
});
Upvotes: 1
Reputation: 191058
This is a perfect case for a Promise
and Promise.all
.
function readFile(name) {
return new Promise((resolve, reject) =>
fs.readFile(name, function (err, data) {
if (err) { reject(err); }
resolve(data);
});
});
}
Promise.all(readFile('file1'), readFile('file2')).then(data => {
var file1 = data[0];
var file2 = data[1];
});
Upvotes: 6