UNPKG

1.15 kBJavaScriptView Raw
1const { createHash } = require('crypto')
2const { createReadStream } = require('fs')
3
4const getStream = require('get-stream')
5const locatePath = require('locate-path')
6
7// Caching a big directory like `node_modules` is slow. However those can
8// sometime be represented by a digest file such as `package-lock.json`. If this
9// has not changed, we don't need to save cache again.
10const getHash = async function(digests, move) {
11 // Moving files is faster than computing hashes
12 if (move || digests.length === 0) {
13 return
14 }
15
16 const digestPath = await locatePath(digests)
17 if (digestPath === undefined) {
18 return
19 }
20
21 const hash = await hashFile(digestPath)
22 return hash
23}
24
25// Hash a file's contents
26const hashFile = async function(path) {
27 const contentStream = createReadStream(path, 'utf8')
28 const hashStream = createHash(HASH_ALGO, { encoding: 'hex' })
29 contentStream.pipe(hashStream)
30 const hash = await getStream(hashStream)
31 return hash
32}
33
34// We need a hashing algoritm that's as fast as possible.
35// Userland CRC32 implementations are actually slower than Node.js SHA1.
36const HASH_ALGO = 'sha1'
37
38module.exports = { getHash }