웹 프론트엔드 JS 튜토리얼 Node.js를 사용하여 압축 및 압축 해제 기능 구현

Node.js를 사용하여 압축 및 압축 해제 기능 구현

Jun 06, 2018 am 09:27 AM
node nodejs 압축 압축을 푼다

이 글에서는 Node.js 기반의 압축 및 압축해제 방법을 주로 소개하고 있으니 참고용으로 올려보겠습니다.

압축 형식

zip과 gzip은 우리가 볼 수 있는 가장 일반적인 두 가지 압축 형식입니다. 물론 gzip은 Windows 사용자가 거의 사용하지 않습니다.

tar는 기본적으로 압축되지 않는 아카이브 형식입니다. 최종 tar 파일을 gzip 형식의 tar.gz 파일로 압축하려면 gzip과 결합해야 하며, 일반적으로 tgz로 축약됩니다.

rar는 왜 언급되지 않나요? 특허로 보호되는 알고리즘이기 때문에 압축 해제 도구는 무료로 얻을 수 있지만 압축 도구는 비용을 지불해야 합니다. 따라서 일반적인 응용 프로그램 시나리오에서는 rar 압축 파일이 거의 제공되지 않습니다.

이 글에서는 Node.js에서 gzip, tar, tgz, zip을 압축하고 압축을 푸는 방법을 각각 소개하겠습니다.

압축되지 않은 파일 라이브러리

이 문서에 사용된 압축되지 않은 파일 라이브러리는 urllib에서 가져온 것입니다. 먼저 이를 복제하고 지정된 디렉터리로 이동해야 합니다.

git clone https://github.com/node-modules/urllib.git nodejs-compressing-demo

gzip

Linux 세계에서 각 도구의 책임은 매우 순수하고 단일합니다. gzip 으로 파일을 압축할 뿐입니다. 폴더를 패키지하고 압축하는 방법은 tar와 관련이 없습니다.

파일을 압축하는 gzip 명령줄

예를 들어, nodejs-compressing-demo/lib/urllib.js 파일을 gzip하려는 경우 urllib.js.gz 파일과 소스 파일을 얻게 됩니다. 삭제됩니다.

$ ls -l nodejs-compressing-demo/lib/urllib.js
-rw-r--r-- 1 a a 31318 Feb 12 11:27 nodejs-compressing-demo/lib/urllib.js

$ gzip nodejs-compressing-demo/lib/urllib.js

$ ls -l nodejs-compressing-demo/lib/urllib.js.gz
-rw-r--r-- 1 a a 8909 Feb 12 11:27 nodejs-compressing-demo/lib/urllib.js.gz

# 还原压缩文件
$ gunzip nodejs-compressing-demo/lib/urllib.js.gz
로그인 후 복사

파일 크기가 31318바이트에서 8909바이트로 3.5배 이상 압축 효과가 감소했습니다.

cat 명령과 결합된 파이프 방법을 통해 파일을 압축하고 다른 파일로 저장할 수도 있습니다.

$ ls -l nodejs-compressing-demo/README.md
-rw-r--r-- 1 a a 13747 Feb 12 11:27 nodejs-compressing-demo/README.md

$ cat nodejs-compressing-demo/README.md | gzip > README.md.gz

$ ls -l README.md.gz
-rw-r--r-- 1 a a 4903 Feb 12 11:50 README.md.gz
로그인 후 복사

Node.js는 gzip을 구현합니다

물론 우리는 실제로 gzip 알고리즘과 도구를 구현하지 않을 것입니다 스크래치. Node.js의 세계에서는 이러한 기본 라이브러리가 이미 준비되어 있으므로 즉시 사용하면 됩니다.

이 기사에서는 압축 모듈을 사용하여 모든 압축 및 압축 해제 코드를 구현합니다.

왜 압축을 선택하나요? 충분한 코드 품질과 단위 테스트 보장을 갖추고 있으며 유지 관리가 활성화되어 있으며 매우 친숙한 API를 갖추고 있으며 스트리밍 인터페이스도 지원합니다.

Promise 인터페이스

const compressing = require('compressing');

// 选择 gzip 格式,然后调用 compressFile 方法
compressing.gzip.compressFile('nodejs-compressing-demo/lib/urllib.js', 'nodejs-compressing-demo/lib/urllib.js.gz')
 .then(() => {
  console.log('success');
 })
 .catch(err => {
  console.error(err);
 });

// 解压缩是反响过程,接口都统一为 uncompress
compressing.gzip.uncompress('nodejs-compressing-demo/lib/urllib.js.gz', 'nodejs-compressing-demo/lib/urllib.js2')
 .then(() => {
  console.log('success');
 })
 .catch(err => {
  console.error(err);
 });
로그인 후 복사

비동기/대기 프로그래밍 모델과 결합하면 코드를 일반적인 비동기 IO 작업으로 작성할 수 있습니다.

const compressing = require('compressing');

async function main() {
 try {
  await compressing.gzip.compressFile('nodejs-compressing-demo/lib/urllib.js',
   'nodejs-compressing-demo/lib/urllib.js.gz');
  console.log('success');
 } catch (err) {
  console.error(err);
 }

 // 解压缩
 try {
  await compressing.gzip.uncompress('nodejs-compressing-demo/lib/urllib.js.gz',
   'nodejs-compressing-demo/lib/urllib.js2');
  console.log('success');
 } catch (err) {
  console.error(err);
 }
}

main();
로그인 후 복사

스트림 인터페이스

스트림 모드에서 프로그래밍할 때 각 스트림의 오류 이벤트를 처리하고 모든 스트림을 수동으로 삭제해야 한다는 점에 특별한 주의가 필요합니다.

fs.createReadStream('nodejs-compressing-demo/lib/urllib.js')
 .on('error', handleError)
 .pipe(new compressing.gzip.FileStream()) // It's a transform stream
 .on('error', handleError)
 .pipe(fs.createWriteStream('nodejs-compressing-demo/lib/urllib.js.gz2'))
 .on('error', handleError);

// 解压缩,就是 pipe 的方向倒转过来
fs.createReadStream('nodejs-compressing-demo/lib/urllib.js.gz2')
 .on('error', handleError)
 .pipe(new compressing.gzip.UncompressStream()) // It's a transform stream
 .on('error', handleError)
 .pipe(fs.createWriteStream('nodejs-compressing-demo/lib/urllib.js3'))
 .on('error', handleError);
로그인 후 복사

스트림의 공식 역압 권장 사항에 따르면 펌프 모듈을 사용하여 스트림 모드 프로그래밍과 협력하고 펌프가 이러한 스트림의 청소 작업을 완료하도록 해야 합니다.

const pump = require('pump');

const source = fs.createReadStream('nodejs-compressing-demo/lib/urllib.js');
const target = fs.createWriteStream('nodejs-compressing-demo/lib/urllib.js.gz2');

pump(source, new compressing.gzip.FileStream(), target, err => {
 if (err) {
  console.error(err);
 } else {
  console.log('success');
 }
});

// 解压缩
pump(fs.createReadStream('nodejs-compressing-demo/lib/urllib.js.gz2'),
  new compressing.gzip.FileStream(),
  fs.createWriteStream('nodejs-compressing-demo/lib/urllib.js3'),
  err => {
 if (err) {
  console.error(err);
 } else {
  console.log('success');
 }
});
로그인 후 복사

Stream 인터페이스의 장점

Stream 인터페이스는 Promise 인터페이스보다 훨씬 복잡해 보이는데 왜 그런 응용 시나리오가 있는 걸까요?

실제로 HTTP 서비스 분야에서는 HTTP 요청 자체가 요청 스트림이기 때문에 스트림 모델이 더 큰 이점을 갖습니다. 업로드된 파일을 gzip 압축으로 반환하려는 경우 업로드된 파일을 저장할 필요가 없습니다. 대신 Stream 인터페이스를 사용하여 파일을 로컬 디스크에 저장하세요.

egg 파일 업로드용 샘플 코드를 사용하여 gzip 압축을 구현하고 약간 수정하여 반환할 수 있습니다.

const pump = require('pump');

class UploadFormController extends Controller {
 // ... other codes

 async upload() {
  const stream = await this.ctx.getFileStream();
  // 直接将压缩流赋值给 ctx.body,实现边压缩边返回的流式响应
  this.ctx.body = pump(stream, new compressing.gzip.FileStream());
 }
}
로그인 후 복사

tar | gzip > tgz

gzip tar가 폴더 패키징을 담당한다는 것을 미리 알 수 있습니다.

예를 들어 nodejs-compressing-dem o 폴더 전체를 파일로 패키징하여 다른 사람에게 보내려는 경우 tar 명령을 사용하면 됩니다.

$ tar -c -f nodejs-compressing-demo.tar nodejs-compressing-demo/

$ ls -l nodejs-compressing-demo.tar
-rw-r--r-- 1 a a 206336 Feb 12 14:01 nodejs-compressing-demo.tar
로그인 후 복사

보시다시피 tar로 패키징한 파일은 일반적으로 무압축이기 때문에 용량이 더 크고 크기도 폴더의 실제 전체 크기에 가깝습니다. 그래서 우리는 포장과 동시에 모두 압축을 하게 됩니다.

$ tar -c -z -f nodejs-compressing-demo.tgz nodejs-compressing-demo/

$ ls -l nodejs-compressing-demo.tgz
-rw-r--r-- 1 a a 39808 Feb 12 14:07 nodejs-compressing-demo.tgz
로그인 후 복사

tar와 tgz의 크기 차이가 5배 이상이므로 네트워크 전송 대역폭이 크게 줄어들 수 있습니다.

Node.js는 tgz

Promise 인터페이스

를 구현합니다. 먼저 압축.tar.compressDir(sourceDir, targetFile)을 사용하여 폴더를 tar 파일로 패키징한 다음 위의 gzip 압축 방법을 사용하여 압축합니다. tar 파일 파일이 tgz 파일로 압축됩니다.

const compressing = require('compressing');

compressing.tar.compressDir('nodejs-compressing-demo', 'nodejs-compressing-demo.tar')
 .then(() => {
  return compressing.gzip.compressFile('nodejs-compressing-demo.tar',
   'nodejs-compressing-demo.tgz');
 });
 .then(() => {
  console.log('success');
 })
 .catch(err => {
  console.error(err);
 });

// 解压缩
compressing.gzip.uncompress('nodejs-compressing-demo.tgz', 'nodejs-compressing-demo.tar')
 .then(() => {
  return compressing.tar.uncompress('nodejs-compressing-demo.tar',
   'nodejs-compressing-demo2');
 });
 .then(() => {
  console.log('success');
 })
 .catch(err => {
  console.error(err);
 });
로그인 후 복사

async/await 프로그래밍 모델과 결합하면 코드 읽기가 더 쉬워집니다.

const compressing = require('compressing');

async function main() {
 try {
  await compressing.tar.compressDir('nodejs-compressing-demo',
   'nodejs-compressing-demo.tar');
  await compressing.gzip.compressFile('nodejs-compressing-demo.tar',
   'nodejs-compressing-demo.tgz');
  console.log('success');
 } catch (err) {
  console.error(err);
 }
 
 // 解压缩
 try {
  await compressing.gzip.uncompress('nodejs-compressing-demo.tgz',
   'nodejs-compressing-demo.tar');
  await compressing.tar.uncompress('nodejs-compressing-demo.tar',
   'nodejs-compressing-demo2');
  console.log('success');
 } catch (err) {
  console.error(err);
 }
}

main();
로그인 후 복사

Stream 인터페이스

compressing.tar.Stream 클래스를 통해 모든 파일과 폴더를 tar 스트림에 동적으로 추가할 수 있습니다. 객체, 매우 유연합니다.

const tarStream = new compressing.tar.Stream();
// dir
tarStream.addEntry('dir/path/to/compress');
// file
tarStream.addEntry('file/path/to/compress');
// buffer
tarStream.addEntry(buffer);
// stream
tarStream.addEntry(stream);

const destStream = fs.createWriteStream('path/to/destination.tgz');
pump(tarStream, new compressing.gzip.FileStream(), destStream, err => {
 if (err) {
  console.error(err);
 } else {
  console.log('success');
 }
});
로그인 후 복사

zip

zip은 실제로 tar + gzip의 "상업적" 조합으로 간주될 수 있습니다. 이를 통해 사용자는 압축 파일과 압축 폴더를 구분할 필요가 없습니다.

zip 명령줄 도구를 사용하여 폴더를 압축하는 예:

$ zip -r nodejs-compressing-demo.zip nodejs-compressing-demo/
 adding: nodejs-compressing-demo/ (stored 0%)
 adding: nodejs-compressing-demo/test/ (stored 0%)
 ...
 adding: nodejs-compressing-demo/.travis.yml (deflated 36%)

$ ls -l nodejs-compressing-demo.*
-rw-r--r-- 1 a a 206336 Feb 12 14:06 nodejs-compressing-demo.tar
-rw-r--r-- 1 a a  39808 Feb 12 14:07 nodejs-compressing-demo.tgz
-rw-r--r-- 1 a a  55484 Feb 12 14:34 nodejs-compressing-demo.zip
로그인 후 복사

tgz와 zip의 파일 크기를 비교하면 기본 압축 매개변수 하에서 gzip이 zip보다 더 나은 효과가 있음을 알 수 있습니다.

Node.js는 zip을 구현합니다

구현 코드는 tar와 유사하지만 기본적으로 압축되어 있으며 gzip 프로세스를 추가할 필요가 없습니다.

const compressing = require('compressing');

compressing.zip.compressDir('nodejs-compressing-demo', 'nodejs-compressing-demo.zip')
 .then(() => {
  console.log('success');
 })
 .catch(err => {
  console.error(err);
 });

// 解压缩
compressing.zip.uncompress('nodejs-compressing-demo.zip', 'nodejs-compressing-demo3')
 .then(() => {
  console.log('success');
 })
 .catch(err => {
  console.error(err);
 });
로그인 후 복사

요약

Node.js 기반의 압축과 압축 해제가 생각보다 쉽나요? 거대한 npm 덕분에 우리는 명령줄 도구를 사용하여 프로그래밍하는 간단한 경험을 할 수 있습니다.

Promise 인터페이스든 Stream 인터페이스든 가장 적합한 시나리오를 선택하시겠습니까?

이 시점에서 가지고 있는 압축 및 압축해제 기능으로 어떤 서비스와 기능을 할 수 있나요?

위 내용은 모두를 위해 제가 정리한 내용입니다. 앞으로 모든 사람에게 도움이 되기를 바랍니다.

관련 기사:

tween.js를 사용하여 트윈 애니메이션 알고리즘 구현

React의 참조에 대한 자세한 설명(자세한 튜토리얼)

JS를 통해 텍스트 간헐적 루프 스크롤 효과를 얻는 방법

위 내용은 Node.js를 사용하여 압축 및 압축 해제 기능 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

nodejs는 백엔드 프레임워크인가요? nodejs는 백엔드 프레임워크인가요? Apr 21, 2024 am 05:09 AM

Node.js는 고성능, 확장성, 크로스 플랫폼 지원, 풍부한 생태계, 개발 용이성 등의 기능을 제공하므로 백엔드 프레임워크로 사용할 수 있습니다.

7-zip 최대 압축률 설정, 7zip을 최소로 압축하는 방법 7-zip 최대 압축률 설정, 7zip을 최소로 압축하는 방법 Jun 18, 2024 pm 06:12 PM

특정 다운로드 사이트에서 다운로드한 압축 패키지는 압축을 푼 후 원본 압축 패키지보다 용량이 더 커지는 것을 확인했습니다. 그 차이는 수십 Kb, 수십 Mb 정도입니다. 클라우드 디스크나 유료 공간에 업로드해도 상관없습니다. 파일이 작을 경우, 파일이 많을 경우 저장 비용이 크게 증가합니다. 나는 그것에 대해 약간의 조사를 했으며 필요하다면 배울 수 있습니다. 압축 수준: 9급 압축 사전 크기: 256 또는 384, 사전을 많이 압축할수록 속도가 느려집니다. 256MB 이전에는 압축률 차이가 더 크고, 384MB 이후에는 압축률 차이가 없습니다. 단어 크기: 최대 273 매개변수: f=BCJ2, 테스트 및 추가 매개변수 압축률이 높아집니다.

nodejs를 mysql 데이터베이스에 연결하는 방법 nodejs를 mysql 데이터베이스에 연결하는 방법 Apr 21, 2024 am 06:13 AM

MySQL 데이터베이스에 연결하려면 다음 단계를 따라야 합니다. mysql2 드라이버를 설치합니다. mysql2.createConnection()을 사용하여 호스트 주소, 포트, 사용자 이름, 비밀번호 및 데이터베이스 이름이 포함된 연결 개체를 만듭니다. 쿼리를 수행하려면 Connection.query()를 사용하세요. 마지막으로 Connection.end()를 사용하여 연결을 종료합니다.

nodejs의 전역 변수는 무엇입니까 nodejs의 전역 변수는 무엇입니까 Apr 21, 2024 am 04:54 AM

Node.js에는 다음과 같은 전역 변수가 존재합니다. 전역 개체: 전역 핵심 모듈: 프로세스, 콘솔, 필수 런타임 환경 변수: __dirname, __filename, __line, __column 상수: undefine, null, NaN, Infinity, -Infinity

nodejs 설치 디렉토리에 있는 npm과 npm.cmd 파일의 차이점은 무엇입니까? nodejs 설치 디렉토리에 있는 npm과 npm.cmd 파일의 차이점은 무엇입니까? Apr 21, 2024 am 05:18 AM

Node.js 설치 디렉터리에는 npm과 npm.cmd라는 두 가지 npm 관련 파일이 있습니다. 차이점은 다음과 같습니다. 확장자가 다릅니다. npm은 실행 파일이고 npm.cmd는 명령 창 바로 가기입니다. Windows 사용자: npm.cmd는 명령 프롬프트에서 사용할 수 있으며, npm은 명령줄에서만 실행할 수 있습니다. 호환성: npm.cmd는 Windows 시스템에만 해당되며 npm은 크로스 플랫폼에서 사용할 수 있습니다. 사용 권장사항: Windows 사용자는 npm.cmd를 사용하고, 기타 운영 체제는 npm을 사용합니다.

PI 노드 교육 : PI 노드 란 무엇입니까? Pi 노드를 설치하고 설정하는 방법은 무엇입니까? PI 노드 교육 : PI 노드 란 무엇입니까? Pi 노드를 설치하고 설정하는 방법은 무엇입니까? Mar 05, 2025 pm 05:57 PM

Pinetwork 노드에 대한 자세한 설명 및 설치 안내서이 기사에서는 Pinetwork Ecosystem을 자세히 소개합니다. Pi 노드, Pinetwork 생태계의 주요 역할을 수행하고 설치 및 구성을위한 전체 단계를 제공합니다. Pinetwork 블록 체인 테스트 네트워크가 출시 된 후, PI 노드는 다가오는 주요 네트워크 릴리스를 준비하여 테스트에 적극적으로 참여하는 많은 개척자들의 중요한 부분이되었습니다. 아직 Pinetwork를 모른다면 Picoin이 무엇인지 참조하십시오. 리스팅 가격은 얼마입니까? PI 사용, 광업 및 보안 분석. Pinetwork 란 무엇입니까? Pinetwork 프로젝트는 2019 년에 시작되었으며 독점적 인 Cryptocurrency Pi Coin을 소유하고 있습니다. 이 프로젝트는 모든 사람이 참여할 수있는 사람을 만드는 것을 목표로합니다.

nodejs와 java 사이에 큰 차이가 있나요? nodejs와 java 사이에 큰 차이가 있나요? Apr 21, 2024 am 06:12 AM

Node.js와 Java의 주요 차이점은 디자인과 기능입니다. 이벤트 중심 대 스레드 중심: Node.js는 이벤트 중심이고 Java는 스레드 중심입니다. 단일 스레드 대 다중 스레드: Node.js는 단일 스레드 이벤트 루프를 사용하고 Java는 다중 스레드 아키텍처를 사용합니다. 런타임 환경: Node.js는 V8 JavaScript 엔진에서 실행되는 반면 Java는 JVM에서 실행됩니다. 구문: Node.js는 JavaScript 구문을 사용하고 Java는 Java 구문을 사용합니다. 목적: Node.js는 I/O 집약적인 작업에 적합한 반면, Java는 대규모 엔터프라이즈 애플리케이션에 적합합니다.

nodejs는 백엔드 개발 언어인가요? nodejs는 백엔드 개발 언어인가요? Apr 21, 2024 am 05:09 AM

예, Node.js는 백엔드 개발 언어입니다. 서버 측 비즈니스 로직 처리, 데이터베이스 연결 관리, API 제공 등 백엔드 개발에 사용됩니다.

See all articles