Node. js - 핵심 모듈 - zlib

2204 단어 NodeJS
9. Zlip
    (1) gzip 압축
    (2) Zlib 대상
         Gzip.createGzip()
         Gzip.createGunzip()
//     
const fs = require('fs');
const zlib = require('zlib');
//         
const rs = fs.createReadStream('./data.txt');

//         
const ws = fs.createWriteStream('./data.txt.gzip');
//   gzip      ,gzip    
const gzip =zlib.createGzip();
//     
rs.pipe(gzip).pipe(ws);

예: 명령 을 사용 하여 압축 파일 을 압축 하고 풀 수 있 습 니 다.
명령 행 입력: node 2. js a. txt a. txt. gzip
//     
const fs = require('fs');
const zlib = require('zlib');
let src;
let dst;
//              
if (process.argv[2]) {
    src = process.argv[2];
} else {
    throw new Error('      ');
}
if (process.argv[3]) {
    dst = process.argv[3];
} else {
    throw new Error('       ');
}
//         
const rs = fs.createReadStream(src);
//         
const ws = fs.createWriteStream(dst);

const gzip =zlib.createGzip();
//     
rs.pipe(gzip).pipe(ws);

압축 풀기: node 3. js a. txt. gzip b. txt
/     
const fs = require('fs');
const zlib = require('zlib');
//       
if (!process.argv[2] && !process.argv[3]) {
    throw new Error('     ');
}
//         
const rs = fs.createReadStream(process.argv[2]);
//         
const ws = fs.createWriteStream(process.argv[3]);
const gzip =zlib.createGunzip();
//     
rs.pipe(gzip).pipe(ws);
console.log('    ');

브 라 우 저 에서 웹 페이지 를 열 고 파일 다운로드:
//    
const http = require('http');
const fs = require('fs');
const zlib = require('zlib');
//  http  
http.createServer((req, res) => {
    const rs = fs.createReadStream('./index.html');
    //               
    if (req.headers['accept-encoding'].indexOf('gzip') != -1) {
        //     
        res.writeHead(200, {
           'content-encoding': 'gzip'
        });
        rs.pipe(zlib.createGzip()).pipe(res);
    } else {
        //   
        rs.pipe(res);
    }
}).listen(8080, () => {
    console.log('http server is running on port 8080');
});

좋은 웹페이지 즐겨찾기