forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtar.ts
More file actions
48 lines (40 loc) · 1.41 KB
/
tar.ts
File metadata and controls
48 lines (40 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { createReadStream } from 'node:fs';
import { normalize } from 'node:path';
import { createGunzip } from 'node:zlib';
import { extract } from 'tar-stream';
/**
* Extract and return the contents of a single file out of a tar file.
*
* @param tarball the tar file to extract from
* @param filePath the path of the file to extract
* @returns the Buffer of file or an error on fs/tar error or file not found
*/
export function extractFile(tarball: string, filePath: string): Promise<Buffer> {
const normalizedFilePath = normalize(filePath);
return new Promise((resolve, reject) => {
const extractor = extract();
extractor.on('entry', (header, stream, next) => {
if (normalize(header.name) !== normalizedFilePath) {
stream.resume();
next();
return;
}
const chunks: Buffer[] = [];
stream.on('data', (chunk) => chunks.push(chunk));
stream.on('error', reject);
stream.on('end', () => {
resolve(Buffer.concat(chunks));
next();
});
});
extractor.on('finish', () => reject(new Error(`'${filePath}' not found in '${tarball}'.`)));
createReadStream(tarball).pipe(createGunzip()).pipe(extractor).on('error', reject);
});
}