node/deps/npm/lib/utils/sha.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

var fs = require("graceful-fs")
, crypto = require("crypto")
2012-06-11 12:29:47 +08:00
, log = require("npmlog")
, binding
try { binding = process.binding("crypto") }
catch (e) { binding = null }
exports.check = check
exports.get = get
function check (file, sum, cb) {
if (!binding) {
2012-06-11 12:29:47 +08:00
log.warn("shasum", "crypto binding not found. Cannot verify shasum.")
return cb()
}
get(file, function (er, actual) {
2012-06-11 12:29:47 +08:00
if (er) {
log.error("shasum", "error getting shasum")
return cb(er)
}
var expected = sum.toLowerCase().trim()
, ok = actual === expected
cb(ok ? null : new Error(
"shasum check failed for "+file+"\n"
+"Expected: "+expected+"\n"
+"Actual: "+actual))
})
}
function get (file, cb) {
if (!binding) {
2012-06-11 12:29:47 +08:00
log.warn("shasum", "crypto binding not found. Cannot verify shasum.")
return cb()
}
var h = crypto.createHash("sha1")
, s = fs.createReadStream(file)
, errState = null
s.on("error", function (er) {
if (errState) return
2012-06-11 12:29:47 +08:00
log.silly("shasum", "error", er)
return cb(errState = er)
}).on("data", function (chunk) {
if (errState) return
2012-06-11 12:29:47 +08:00
log.silly("shasum", "updated bytes", chunk.length)
h.update(chunk)
}).on("end", function () {
if (errState) return
var actual = h.digest("hex").toLowerCase().trim()
2012-06-11 12:29:47 +08:00
log.info("shasum", actual+"\n"+file)
cb(null, actual)
})
}