Skip to content

Commit

Permalink
Lazy load crypto module
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Jul 20, 2019
1 parent e680feb commit f9460a7
Showing 1 changed file with 23 additions and 19 deletions.
42 changes: 23 additions & 19 deletions src/hashFile.mjs
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import fs from "./fs-promises.js";
import crypto from "crypto";

export default fileOrString =>
new Promise((resolve, reject) => {
const hash = crypto.createHash("sha1");
const HASH_ALGORITHM = "sha1";
const HASH_OUTPUT = "hex";

fs.access(fileOrString, fs.constants.R_OK)
.then(() => {
const input = fs.createReadStream(fileOrString);
export default fileOrString =>
import("crypto")
.then(module => module.default)
.then(({ createHash }) => createHash(HASH_ALGORITHM))
.then(hash =>
fs
.access(fileOrString, fs.constants.R_OK)
.then(() => {
const input = fs.createReadStream(fileOrString);

input.on("error", err => reject(err));
input.on("data", data => hash.update(data));
input.on("end", () => {
resolve(hash.digest("hex"));
});
})
.catch(() => {
// Plain string handling
hash.update(fileOrString);
resolve(hash.digest("hex"));
});
});
input.on("error", err => reject(err));
input.on("data", data => hash.update(data));
input.on("end", () => {
resolve(hash.digest(HASH_OUTPUT));
});
})
.catch(() => {
// Plain string handling
hash.update(fileOrString);
resolve(hash.digest(HASH_OUTPUT));
})
);

0 comments on commit f9460a7

Please sign in to comment.