import crypto from 'crypto';
export const getChecksum: (_: PathLike) => Promise<string> = (path: PathLike) =>
new Promise(resolve => {
const hash = crypto.createHash('md5');
const input = fs.createReadStream(path);
input.on('data', chunk => {
hash.update(chunk);
});
input.on('close', () => {
resolve(hash.digest('hex'));
});
});
Given the function, it can accept a file path, and perform hash.update
while streaming the file, I’m trying to write an unit test like below
describe('getChecksum()', () => {
afterEach(() => {
vol.reset();
});
it('should generate consistent checksum', async () => {
vol.fromJSON(
{
'./some/README.md': '1',
'./some/index.js': '2',
},
'/app'
);
const result = await getChecksum('/app/some/index.js');
expect(result).toBe('c81e728d9d4c2f636f067f89cc14862c');
});
});
From the Unit Test above, assertion was able to perform correctly, however, I’m hitting error below
● getChecksum() › should generate consistent checksum
Error [ERR_CRYPTO_HASH_FINALIZED] [ERR_CRYPTO_HASH_FINALIZED]: Digest already called
63 |
64 | input.on('close', () => {
> 65 | resolve(hash.digest('hex'));
| ^
66 | });
67 | });
68 |
Not too sure which part has gone wrong?