aboutsummaryrefslogtreecommitdiffstats
path: root/qt-qml/src/unzipper.ts
blob: b6f11eb3d739b2babb1a319216a2653271b7048a (plain)
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
49
50
51
52
53
54
55
56
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only

import * as yauzl from 'yauzl';
import { Writable } from 'stream';

export type Entry = yauzl.Entry;

export async function unzip(
  inputPath: string,
  streamProvider: (entry: yauzl.Entry) => Writable | null
) {
  return new Promise<void>((resolve, reject) => {
    const callback = (error: Error | null, zipFile: yauzl.ZipFile) => {
      if (error) {
        reject(error);
        return;
      }

      zipFile.readEntry();
      zipFile.on('entry', (entry: yauzl.Entry) => {
        const writer = streamProvider(entry);
        if (writer === null) {
          zipFile.readEntry();
          return;
        }

        zipFile.openReadStream(entry, (e, reader) => {
          if (e) {
            reject(e);
            return;
          }

          reader.pipe(writer);
          reader.on('end', () => {
            zipFile.readEntry();
          });

          reader.on('error', reject);
          writer.on('error', reject);
        });
      });

      zipFile.on('end', () => {
        zipFile.close();
        resolve();
      });

      zipFile.on('error', () => {
        reject(new Error('zipfile error'));
      });
    };

    yauzl.open(inputPath, { lazyEntries: true }, callback);
  });
}