file hash in node

  1. 1. 利用node中的加密模块crypto计算文件的hash值

利用node中的加密模块crypto计算文件的hash值

readStream的方式读取文件并同时使用crypto.createHash计算hash值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
* usage: node hash.js fileToHash
*/
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const file = path.resolve(process.argv[2])
const rs = fs.createReadStream(file, { highWaterMark: 4194304 })
const start = (new Date()).getTime()
const type = 'sha256' // 'md5', 'sha512', etc.
const hash = crypto.createHash(type).setEncoding('hex')
const size = fs.lstatSync(file).size
rs.on('end', () => {
hash.end()
console.log('file: ', file, '\nsize: ', size, 'B\ntime: ', (new Date()).getTime() - start, 'ms\nhash: ', hash.read())
})
rs.pipe(hash)