Code ví dụ Node.js nén, giải nén file – module Zlib

Code ví dụ Node.js nén, giải nén file – module Zlib

(Xem thêm: Hướng dẫn Node.js)

Module sử dụng

Để thực hiện nén/giải nén file (zip/unzip) trong node.js ta sử dụng module zlib

zlib là module có sẵn khi cài node.js, để include zlib vào project ta dùng method

var zlib = require('zlib');

Nén file (zip)

Dưới đây là code ví dụ nén file hello.txt thành file hello.txt.gzip

var zlib = require('zlib');
var fs = require('fs');

var gzip = zlib.createGzip();
var r = fs.createReadStream('hello.txt');
var w = fs.createWriteStream('hello.txt.gzip');
r.pipe(gzip).pipe(w);

console.log('done');

Đầu vào của method fs.createReadStream và fs.createWriteStream sẽ là url của file được dùng để nén và url của file kết quả sau khi được nén

Giải nén file (unzip)

Đây là code ví dụ giải nén file hello.txt.gzip thành file unzip.txt.

var zlib = require('zlib');
var fs = require('fs');

var unzip = zlib.createUnzip();

var read = fs.createReadStream('hello.txt.gz');
var write = fs.createWriteStream('unzip.txt');

read.pipe(unzip).pipe(write);	
console.log("unZipped Successfully");

Một số method khác của zlib

Method Mô tả
constants Returns an object containing Zlib constants
createDeflate() Creates a Deflate object
createDeflateRaw() Creates a DeflateRaw object
createGunzip() Creates a Gunzip object
createGzip() Creates a Gzip object
createInflate() Creates a Inflate object
createInflateRaw() Creates a InflateRaw object
createUnzip() Creates a Unzip object
deflate() Compress a string or buffer, using Deflate
deflateSync() Compress a string or buffer, syncronously, using Deflate
deflateRaw() Compress a string or buffer, using DeflateRaw
deflateRawSync() Compress a string or buffer, syncronously, using DeflateRaw
gunzip() Compress a string or buffer, using Gunzip
gunzipSync() Compress a string or buffer, syncronously, using Gunzip
gzip() Compress a string or buffer, using Gzip
gzipSync() Compress a string or buffer, syncronously, using Gzip
inflate() Decompress a string or buffer, using Inflate
inflateSync() Decompress a string or buffer, syncronously, using Inflate
inflateRaw() Decompress a string or buffer, using InflateRaw
inflateRawSync() Decompress a string or buffer, syncronously, using InflateRaw
unzip() Decompress a string or buffer, using Unzip
unzipSync() Decompress a string or buffer, syncronously, using Unzip
Okay, Done!
Download code ví dụ trên tại đây.
——————–
References:
stackjava.com