UNPKG

fs-nextra

Version:

Node.js fs next-gen extra (nextra) methods.

69 lines 2.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Untar = void 0; const stream_1 = require("stream"); const Header_1 = require("./Header"); function breakSync(next) { setImmediate(() => next()); } class Untar extends stream_1.Writable { constructor() { super(...arguments); this.header = null; this.file = Buffer.alloc(0); this.totalRead = 0; this.recordSize = 512; this.queue = []; } _write(data, encoding, next) { this.file = Buffer.concat([this.file, data], this.file.length + data.length); if (this.file.length === 0) return breakSync(next); // file if (this.header) { if (this.file.length >= this.header.size) { if (this.listenerCount('file')) this.emit('file', this.header, this.slice(this.header.size)); else this.queue.push({ header: this.header, file: this.slice(this.header.size) }); this.header = null; return this._write(Buffer.alloc(0), encoding, next); } return breakSync(next); } // Remove extra bits between files if (this.totalRead % this.recordSize) { this.slice(Math.min(this.recordSize - (this.totalRead % this.recordSize), this.file.length)); return this._write(Buffer.alloc(0), encoding, next); } /* istanbul ignore next: Hard to test, requires the leftover of a chunk to be less than the size of a header block */ if (this.file.length < this.recordSize) return breakSync(next); this.header = new Header_1.Header(this.slice(this.recordSize)); return this._write(Buffer.alloc(0), encoding, next); } slice(length) { const buffer = this.file.slice(0, length); this.file = this.file.slice(length); this.totalRead += length; return buffer; } next() { if (this.queue.length) return Promise.resolve(this.queue.shift()); /* istanbul ignore next: Hard to produce in CI */ if (!this.writable) return Promise.reject(null); return new Promise((resolve) => { this.once('file', (header, file) => { resolve({ header, file }); }); }); } async *files() { while (this.queue.length || this.writable) yield this.next(); } } exports.Untar = Untar; //# sourceMappingURL=Untar.js.map