From 558f3fdecd0899b26f3f856b3690d306440d46e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me> Date: Wed, 9 Aug 2023 19:44:08 +0200 Subject: [PATCH] Add ArchiveHelper --- helpers/ArchiveHelper.ts | 69 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 helpers/ArchiveHelper.ts diff --git a/helpers/ArchiveHelper.ts b/helpers/ArchiveHelper.ts new file mode 100644 index 0000000..6104299 --- /dev/null +++ b/helpers/ArchiveHelper.ts @@ -0,0 +1,69 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import tar from 'tar-stream'; +import stream from 'node:stream'; +import { Writable } from 'stream'; +import zlib from 'zlib'; + + +class ArchiveHelper { + private async explore(absoluteBasePath: string, rootPath: string, pack: tar.Pack) { + for ( let file of await fs.promises.readdir(rootPath) ) { + if ( file === 'output.tar' ) { + continue; + } + file = path.join(rootPath, file); + const stat = await fs.promises.stat(file); + if ( stat.isDirectory() ) { + await this.explore(absoluteBasePath, file, pack); + continue; + } + const entry = pack.entry({ + name: file.replace(absoluteBasePath, ''), + size: stat.size + }, (err) => { + if ( err ) { + throw err; + } + }); + const stream = fs.createReadStream(file); + stream.pipe(entry); + } + } + + private async compress(folderPath: string, tarDataStream: stream.Writable) { + const pack = tar.pack(); + + await this.explore(folderPath, folderPath, pack); + + pack.pipe(zlib.createGzip()).pipe(tarDataStream); + pack.finalize(); + } + + public async getBase64(folderPath: string): Promise<string> { + let data: any; + const tarDataStream = new stream.Writable({ + write(this: Writable, chunk: Buffer, _encoding: BufferEncoding, next: (error?: Error | null) => void) { + if ( data ) { + data += chunk.toString('hex'); + } else { + data = chunk.toString('hex'); + } + next(); + } + }); + + await this.compress(folderPath, tarDataStream); + + await (new Promise((resolve, reject) => { + tarDataStream.on('close', () => { + resolve(0); + }); + })); + + return Buffer.from(data, 'hex').toString('base64'); + } +} + + +export default new ArchiveHelper(); \ No newline at end of file -- GitLab