Skip to content

Commit

Permalink
Merge pull request #226 from fqueze/faster-getHash
Browse files Browse the repository at this point in the history
Avoid utf8 encoding binary image files in getHash.
  • Loading branch information
zachleat authored Oct 1, 2024
2 parents 2f8d196 + 2853c10 commit 803d902
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions img.js
Original file line number Diff line number Diff line change
Expand Up @@ -368,11 +368,17 @@ class Image {
if(fs.existsSync(this.src)) {
let fileContents = this.getFileContents();

// remove all newlines for hashing for better cross-OS hash compatibility (Issue #122)
let fileContentsStr = fileContents.toString();
let firstFour = fileContentsStr.trim().slice(0, 5);
if(firstFour === "<svg " || firstFour === "<?xml") {
fileContents = fileContentsStr.replace(/\r|\n/g, '');
// If the file starts with whitespace or the '<' character, it might be SVG.
// Otherwise, skip the expensive buffer.toString() call
// (no point in unicode encoding a binary file)
let fileContentsPrefix = fileContents.slice(0, 1).toString().trim();
if (!fileContentsPrefix || fileContentsPrefix[0] == "<") {
// remove all newlines for hashing for better cross-OS hash compatibility (Issue #122)
let fileContentsStr = fileContents.toString();
let firstFour = fileContentsStr.trim().slice(0, 5);
if(firstFour === "<svg " || firstFour === "<?xml") {
fileContents = fileContentsStr.replace(/\r|\n/g, '');
}
}

hash.update(fileContents);
Expand Down

0 comments on commit 803d902

Please sign in to comment.