Create a Zip Archive (Node.js)

JS
S
JavaScript

Simple script to create ZIP/TARball archives with Node.js

1import * as fs from 'fs';
2import archiver from 'archiver';
3
4import logService from './log';
5
6class FileZipperService {
7  public data: any[];
8  constructor() {
9    logService.log('info', 'New File Zipper Created');
10  }
11
12  public async compressCsvFile(fileName: string): Promise<string> {
13    const zippedFileName = `${fileName}.zip`;
14    return new Promise((resolve, reject) => {
15      const output = fs.createWriteStream(zippedFileName);
16      const archive = archiver('zip', {
17        zlib: { level: 9 }
18      });
19      output.on('end', () => {
20        logService.log('info', 'Zipper Data has been drained');
21      });
22      output.on('close', () => {
23        logService.log('info', `${archive.pointer()} total bytes`);
24        logService.log(
25          'info',
26          'Zipper archiver has been finalized and the output file descriptor has closed.'
27        );
28        resolve(zippedFileName);
29      });
30      archive.on('error', (err) => {
31        logService.log('error', 'Zipper failed to compress CSV', err);
32        reject(err);
33      });
34      archive.on('warning', (err) => {
35        if (err.code === 'ENOENT') {
36          logService.log('error', 'Zipper warning to compress CSV ENOENT', err);
37          reject(err);
38        } else {
39          logService.log('error', 'Zipper warning to compress CSV', err);
40          reject(err);
41        }
42      });
43      // Pipe file into archive & finish
44      const file1 = __dirname + `/../../${fileName}`;
45      archive.append(fs.createReadStream(file1), { name: fileName });
46      archive.pipe(output);
47      archive.finalize();
48    });
49  }
50}
51export { FileZipperService };
52

Created on 6/6/2020