-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathchecksum.js
92 lines (68 loc) · 1.91 KB
/
checksum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*!
* checksum
* Copyright(c) 2013 Daniel D. Shaw <dshaw@dshaw.com>
* MIT Licensed
*/
/**
* Module dependencies
*/
var crypto = require('crypto')
, fs = require('fs')
/**
* Exports
*/
module.exports = checksum
checksum.file = checksumFile
/**
* Checksum
*/
function checksum (value, options) {
options || (options = {})
if (!options.algorithm) options.algorithm = 'sha256'
if (!options.encoding) options.encoding = 'hex'
var hash = crypto.createHash(options.algorithm)
// http://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm
if (!hash.write) {
// pre-streaming crypto API in node < v0.9
hash.update(value)
return hash.digest(options.encoding)
} else {
// v0.9+ streaming crypto
// http://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
hash.write(value)
return hash.digest(options.encoding)
}
}
/**
* Checksum File
*/
function checksumFile (filename, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
options || (options = {})
if (!options.algorithm) options.algorithm = 'sha256'
if (!options.encoding) options.encoding = 'hex'
fs.stat(filename, function (err, stat) {
if (!err && !stat.isFile()) err = new Error('Not a file')
if (err) return callback(err)
var hash = crypto.createHash(options.algorithm)
, fileStream = fs.createReadStream(filename)
if (!hash.write) { // pre-streaming crypto API in node < v0.9
fileStream.on('data', function (data) {
hash.update(data)
})
fileStream.on('end', function () {
callback(null, hash.digest(options.encoding))
})
} else { // v0.9+ streaming crypto
hash.setEncoding(options.encoding)
fileStream.pipe(hash, { end: false })
fileStream.on('end', function () {
hash.end()
callback(null, hash.read())
})
}
})
}