UNPKG

@alinex/datastore

Version:

Read, work and write data structures from and to differents locations and formats.

80 lines 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compress = exports.uncompress = void 0; const path_1 = require("path"); const debug_1 = require("debug"); const tar = require("tar-stream"); const streamBuffers = require("stream-buffers"); const lzma = require("lzma"); const core_1 = require("@alinex/core"); const debug = debug_1.default('datastore:compression:tar'); exports.uncompress = (async function (parsedUri, buffer, options) { debug(`uncompressing ${path_1.basename(parsedUri.pathname)}`); let archivePath = parsedUri.hash && parsedUri.hash.substr(1); buffer = await new Promise((resolve, reject) => { lzma.decompress(buffer, (result, error) => { if (error) return reject(error); resolve(Buffer.from(result)); }); }); const writer = new streamBuffers.WritableStreamBuffer(); const reader = new streamBuffers.ReadableStreamBuffer(); reader.put(buffer); reader.stop(); return new Promise(resolve => { debug(`extracting ${archivePath}`); var extract = tar.extract(); extract.on('finish', resolve); extract.on('entry', function (header, stream, next) { stream.on('end', next); if (archivePath) { if (header.name == archivePath) { stream.pipe(writer); } else { stream.resume(); } } else { archivePath = header.name; parsedUri.hash = `#${archivePath}`; stream.pipe(writer); } }); reader.pipe(extract); }).then(() => { const result = writer.getContents(); if (!result) throw new Error('Found no content in archive.'); return result; }); }); exports.compress = (async function (parsedUri, buffer, options) { debug(`compressing ${path_1.basename(parsedUri.pathname)}`); if (!parsedUri.hash) throw new core_1.ExitError('No file specified in hash part of URL.'); let archivePath = parsedUri.hash && parsedUri.hash.substr(1); const writer = new streamBuffers.WritableStreamBuffer(); buffer = await new Promise(resolve => { debug(`including as ${archivePath}`); writer.on('finish', resolve); var pack = tar.pack(); pack.entry({ name: archivePath }, buffer); pack.finalize(); pack.pipe(writer); }).then(() => { const result = writer.getContents(); if (!result) throw new Error('Found no content in archive.'); return result; }); return new Promise((resolve, reject) => { lzma.compress(buffer, (options && options.compressionLevel) || 9, (result, error) => { if (error) return reject(error); resolve(Buffer.from(result)); }); }); }); //# sourceMappingURL=tlz.js.map