From dc83813fd503da4e89888245c0361a6e75945de7 Mon Sep 17 00:00:00 2001 From: Markus Tacker Date: Wed, 31 Jul 2024 17:24:37 +0200 Subject: [PATCH] feat: export hashFile --- src/hasFile.spec.ts | 15 +++++++++++++++ src/hashFile.ts | 18 ++++++++++++++++++ src/hashFolder.ts | 19 ++----------------- 3 files changed, 35 insertions(+), 17 deletions(-) create mode 100644 src/hasFile.spec.ts create mode 100644 src/hashFile.ts diff --git a/src/hasFile.spec.ts b/src/hasFile.spec.ts new file mode 100644 index 0000000..443b51b --- /dev/null +++ b/src/hasFile.spec.ts @@ -0,0 +1,15 @@ +import { describe, it } from 'node:test' +import assert from 'node:assert/strict' +import path from 'node:path' +import { hashFile } from './hashFile.js' +import { fileURLToPath } from 'node:url' +const __dirname = fileURLToPath(new URL('.', import.meta.url)) + +void describe('hashFile', () => { + void it('should calculate correct MD5 hash value for a file', async () => { + const filePath = path.join(__dirname, 'test-folder', 'test.txt') + const expectedMd5 = '35fd70b6138a64d64c376a6549d6bf57' + const actualMd5 = await hashFile(filePath) + assert.equal(actualMd5, expectedMd5) + }) +}) diff --git a/src/hashFile.ts b/src/hashFile.ts new file mode 100644 index 0000000..c57a130 --- /dev/null +++ b/src/hashFile.ts @@ -0,0 +1,18 @@ +import { createHash } from 'crypto' +import { createReadStream } from 'fs' + +export const hashFile = async (file: string): Promise => { + const hash = createHash('md5') + const content = createReadStream(file) + + return new Promise((resolve, reject) => { + content.pipe(hash) + content + .on('close', () => { + return resolve(hash.digest('hex')) + }) + .on('error', (error) => { + return reject(error) + }) + }) +} diff --git a/src/hashFolder.ts b/src/hashFolder.ts index fc9b0d8..73bd6e6 100644 --- a/src/hashFolder.ts +++ b/src/hashFolder.ts @@ -1,22 +1,7 @@ import { createHash } from 'node:crypto' -import { createReadStream, readdirSync, statSync } from 'node:fs' +import { readdirSync, statSync } from 'node:fs' import { join } from 'node:path' - -const hashFile = async (file: string): Promise => { - const hash = createHash('md5') - const content = createReadStream(file) - - return new Promise((resolve, reject) => { - content.pipe(hash) - content - .on('close', () => { - return resolve(hash.digest('hex')) - }) - .on('error', (error) => { - return reject(error) - }) - }) -} +import { hashFile } from './hashFile.js' const generateMd5ForFolder = async ( path: string,