| 19 | * @returns the Buffer of file or an error on fs/tar error or file not found |
| 20 | */ |
| 21 | export function extractFile(tarball: string, filePath: string): Promise<Buffer> { |
| 22 | const normalizedFilePath = normalize(filePath); |
| 23 | |
| 24 | return new Promise((resolve, reject) => { |
| 25 | const extractor = extract(); |
| 26 | |
| 27 | extractor.on('entry', (header, stream, next) => { |
| 28 | if (normalize(header.name) !== normalizedFilePath) { |
| 29 | stream.resume(); |
| 30 | next(); |
| 31 | |
| 32 | return; |
| 33 | } |
| 34 | |
| 35 | const chunks: Buffer[] = []; |
| 36 | stream.on('data', (chunk) => chunks.push(chunk)); |
| 37 | stream.on('error', reject); |
| 38 | stream.on('end', () => { |
| 39 | resolve(Buffer.concat(chunks)); |
| 40 | next(); |
| 41 | }); |
| 42 | }); |
| 43 | |
| 44 | extractor.on('finish', () => reject(new Error(`'${filePath}' not found in '${tarball}'.`))); |
| 45 | |
| 46 | createReadStream(tarball).pipe(createGunzip()).pipe(extractor).on('error', reject); |
| 47 | }); |
| 48 | } |