How To Check If Two Files Have The Same Content?
Solution 1:
Surprisingly, no one has suggested Buffer.equals. That seems to be the fastest and simplest approach and has been around since v0.11.
So your code would become tmpBuf.equals(testBuf)
Solution 2:
You have 3 solutions:
First:
Compare the result strings
tmpBuf.toString() === testBuf.toString();
Second:
Using a loop to read the buffers byte by byte
var index = 0,
length = tmpBuf.length,
match = true;
while (index < length) {
if (tmpBuf[index] === testBuf[index]) {
index++;
} else {
match = false;
break;
}
}
match; // true -> contents are the same, false -> otherwise
Third:
Using a third-party module like buffertools and buffertools.compare(buffer, buffer|string) method.
Solution 3:
In should.js
you can use .eql
to compare Buffer's instances:
> var buf1 = newBuffer('abc');
undefined
> var buf2 = newBuffer('abc');
undefined
> var buf3 = newBuffer('dsfg');
undefined
> buf1.should.be.eql(buf1)
...
> buf1.should.be.eql(buf2)
...
> buf1.should.be.eql(buf3)
AssertionError: expected <Buffer616263> to equal <Buffer64736667>
...
>
Solution 4:
Solution using file-compare
and node-temp
:
it('should return test2.json as a stream', function (done) {
var writeStream = temp.createWriteStream();
temp.track();
var req = api.get('/files/7386afde8992');
req.on('end', function() {
comparator.compare(writeStream.path, TEST2_JSON_FILE, function(result, err) {
if (err) {
return done(err);
}
result.should.true;
done();
});
});
req.pipe(writeStream);
});
Solution 5:
for comparing large files e.g. images when asserting file uploads a comparison of buffers or strings with should.eql
takes ages. i recommend asserting the buffer hash with the crypto module:
const buf1Hash = crypto.createHash('sha256').update(buf1).digest();
const buf2Hash = crypto.createHash('sha256').update(buf2).digest();
buf1Hash.should.eql(buf2Hash);
an easier approach is asserting the buffer length like so:
buf1.length.should.eql(buf2.length)
instead of using shouldjs as assertion module you can surely use a different tool
Post a Comment for "How To Check If Two Files Have The Same Content?"