Asked 7 years ago
9 Feb 2017
Views 4928
yogi

yogi posted

how to make zip in Node JS?

i want to make zip file from given some xls and text file , is that possible with Node JS
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

node-zip will help to make zip / unzip the files
install node-zip in Node JS

npm install node-zip


Example ::

var fs = require('fs');
var path = require('path');
var zip = new require('node-zip')();
zip.file('some.txt', fs.readFileSync(path.join(__dirname, 'some.txt')));
var data = zip.generate({ base64:false, compression: 'DEFLATE' });
fs.writeFileSync('test.zip', data, 'binary');


will output test.zip

one can add multiple file by file function like this

zip.file('some.txt', fs.readFileSync(path.join(__dirname, 'some.txt')));
zip.file('some2.txt', fs.readFileSync(path.join(__dirname, 'some2.txt')));
shyam

shyam
answered Nov 30 '-1 00:00

node-native-zip is native module without any dependency , help to archive , make zip from text input or files in Node JS

install node-native-zip in Node JS

npm install node-native-zip


How to make zip file with node js ?
lets see one example

var fs = require("fs");
    var zip = require("node-native-zip");

    var archive = new zip();

    archive.add("one.txt", new Buffer("Hello world", "utf8"));

    var buffer = archive.toBuffer();
    fs.writeFile("./one.zip", buffer, function () {
        console.log("Finished");
    });

Rasi

Rasi
answered Nov 30 '-1 00:00

Zlib is useful module to make compression in Gzip and Deflate/Inflate format.

dont need to install Zlib module . its come with Node . so lets start work with it


var zlib = require('zlib');

require('zlib') provide us instance of module .

createGzip() function provide us gzip format zlib instance

const gzip = zlib.createGzip();


lets read a file through fs module

const fs = require('fs');
const inp = fs.createReadStream('test.txt');


createReadStream() will streams from which data can be read

now create another stream to write by createWriteStream

const out = fs.createWriteStream('text.txt.gz');


now lets write zip from text file

inp.pipe(gzip).pipe(out);

Compressing a stream by piping the source stream data through a zlib stream into a destination

final code

gzip.js

var zlib = require('zlib');
const gzip = zlib.createGzip();
const fs = require('fs');
const inp = fs.createReadStream('test.txt');
const out = fs.createWriteStream('text.txt.gz');
inp.pipe(gzip).pipe(out);
Post Answer