archiver compressed file in nodejs

Solutions on MaxInterview for archiver compressed file in nodejs by the best coders in the world

showing results for - "archiver compressed file in nodejs"
Maria José
27 Jan 2020
1npm install archiver --save
2
3// require modules
4var fs = require('fs');
5var archiver = require('archiver');
6
7// create a file to stream archive data to.
8var output = fs.createWriteStream(__dirname + '/example.zip');
9//Set the compression format to zip
10var archive = archiver('zip', {
11    zlib: { level: 9 } // Sets the compression level.
12});
13
14// listen for all archive data to be written
15// 'close' event is fired only when a file descriptor is involved
16output.on('close', function() {
17    console.log(archive.pointer() + ' total bytes');
18    console.log('archiver has been finalized and the output file descriptor has closed.');
19});
20
21// This event is fired when the data source is drained no matter what was the data source.
22// It is not part of this library but rather from the NodeJS Stream API.
23// @see:   https://nodejs.org/api/stream.html#stream_event_end
24output.on('end', function() {
25    console.log('Data has been drained');
26});
27
28// good practice to catch this error explicitly
29archive.on('error', function(err) {
30    throw err;
31});
32// pipe archive data to the file
33archive.pipe(output);
34// append a file from stream
35var file1 = __dirname + '/file1.txt';
36archive.append(fs.createReadStream(file1), { name: 'file1.txt' });
37
38// append a file from string
39archive.append('string cheese!', { name: 'file2.txt' });
40// append a file from buffer
41var buffer3 = Buffer.from('buff it!');
42archive.append(buffer3, { name: 'file3.txt' });
43
44// append a file
45archive.file('file1.txt', { name: 'file4.txt' });
46
47// append files from a sub-directory and naming it `new-subdir` within the archive
48archive.directory('subdir/', 'new-subdir');
49
50// append files from a sub-directory, putting its contents at the root of archive
51archive.directory('subdir/', false);
52
53// append files from a glob pattern
54archive.glob('subdir/*.txt');
55
56// finalize the archive (ie we are done appending files but streams have to finish yet)
57// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
58archive.finalize();
59