>  기사  >  웹 프론트엔드  >  nodejs 배포 압축 패키지 업로드

nodejs 배포 압축 패키지 업로드

WBOY
WBOY원래의
2023-05-08 11:42:07720검색

현대 웹 개발에서는 Node.js를 사용하여 백엔드 애플리케이션을 구축하는 것이 추세가 되었습니다. 애플리케이션이 지속적으로 업데이트됨에 따라 업데이트된 새 버전을 서버에 배포해야 하는 경우가 많습니다. 따라서 이 기사에서는 빠르고 간단하며 효율적인 애플리케이션 업데이트를 달성하기 위해 Node.js를 사용하여 압축 패키지를 배포 및 업로드하는 방법을 소개합니다.

  1. 압축된 파일

업로드하기 전에 배포해야 하는 파일을 Zip 또는 tar.gz 파일로 압축해야 합니다. Node.js를 사용하여 파일 압축을 완료하는 것은 매우 간단합니다. 파일 압축을 쉽게 수행하려면 Node.js에 내장된 "zlib" 및 "fs" 모듈만 사용하면 됩니다. 다음은 간단한 압축 코드입니다.

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

const srcFileName = 'srcFile.txt';
const destFileName = 'srcFile.txt.gz';

// 创建压缩流
const gzip = zlib.createGzip();
const inp = fs.createReadStream(srcFileName);
const out = fs.createWriteStream(destFileName);

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

console.log('文件压缩成功!');

위 코드를 나중에 사용할 수 있도록 함수로 캡슐화할 수 있습니다.

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

function compress(file) {
  const gzip = zlib.createGzip();
  const src = fs.createReadStream(file);
  const dest = fs.createWriteStream(file + '.gz');

  src.pipe(gzip).pipe(dest);

  console.log(`文件 ${file} 压缩成功!`);
}

"파일"은 압축해야 하는 파일의 이름으로, 상대 경로 또는 절대 경로.

  1. 파일 업로드

파일 압축이 완료되면 압축된 파일을 서버에 업로드해야 합니다. 여기서는 타사 모듈을 사용하여 파일 업로드 기능을 구현할 수 있습니다. 일반적으로 사용되는 모듈은 파일 업로드 작업을 처리하는 데 도움이 되는 효율적인 양식 구문 분석 모듈인 "formidable"입니다.

먼저 "formidable"을 설치해야 합니다:

npm install formidable --save

그런 다음 다음 코드를 사용하여 파일 업로드 기능을 구현할 수 있습니다.

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      const oldPath = files.file.path;
      const newPath = __dirname + '/uploads/' + files.file.name;

      fs.rename(oldPath, newPath, (err) => {
        if (err) throw err;
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.end('文件上传成功!');
      });
    });

    return;
  }
}).listen(8080);

console.log('服务器启动成功!');

위 코드에 표시된 대로 수신 포트 8080을 사용하여 HTTP 서버를 생성합니다. . 클라이언트가 URL "/upload"를 사용하여 POST 요청을 요청하면 "formidable"을 사용하여 POST 요청의 파일 데이터를 구문 분석합니다. 구문 분석 후 파일 이름, 파일 크기, 파일 형식 등 업로드된 파일에 대한 관련 정보를 얻을 수 있습니다. 그런 다음 파일을 임시 경로에서 업로드 디렉터리로 이동합니다.

"형성 가능한" 구문 분석을 사용할 때 여러 파일 업로드를 지원하려면 "다중"을 true로 설정해야 한다는 점에 유의해야 합니다. 다른 매개변수를 설정하여 업로드된 파일의 크기, 저장 경로 등을 제어할 수도 있습니다.

  1. 파일 압축 해제

서버가 압축 파일을 수신한 후 업데이트 작업을 시작하기 전에 파일의 압축을 풀어야 합니다. Node.js를 사용하여 파일 압축을 푸는 것도 매우 간단합니다. Node.js에 내장된 "zlib" 및 "fs" 모듈을 사용하면 됩니다. 다음은 간단한 압축 해제 코드 구현입니다.

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

const srcFileName = 'srcFile.txt.gz';
const destFileName = 'srcFile.txt';

// 创建解压流
const gunzip = zlib.createGunzip();
const inp = fs.createReadStream(srcFileName);
const out = fs.createWriteStream(destFileName);

inp.pipe(gunzip).pipe(out);

console.log('文件解压成功!');

압축 함수와 동일하며 나중에 사용할 수 있도록 위 코드를 함수로 캡슐화할 수도 있습니다.

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

function uncompress(file) {
  const gunzip = zlib.createGunzip();
  const src = fs.createReadStream(file);
  const dest = fs.createWriteStream(file.replace('.gz', ''));

  src.pipe(gunzip).pipe(dest);

  console.log(`文件 ${file} 解压成功!`);
}

"파일"은 압축 해제해야 하는 압축 파일의 이름입니다. 압축이 풀린 경로인가요, 아니면 절대 경로인가요?

  1. Deploy update

압축해제 완료 후, 해당 파일을 애플리케이션이 실행 중인 디렉터리로 이동하고 원본 애플리케이션 파일을 덮어쓰면 배포 및 업데이트 작업이 한번 완료됩니다. 다음은 간단한 코드 구현입니다.

const fs = require('fs');
const path = require('path');

const appDir = 'app';

function deploy(file) {
  const fileName = path.basename(file);
  const destPath = path.join(appDir, fileName);

  fs.copyFile(file, destPath, (err) => {
    if (err) throw err;
    console.log(`文件 ${fileName} 部署成功!`);
  });
}

"파일"은 배포해야 하는 압축이 풀린 파일 이름으로, 상대 경로 또는 절대 경로일 수 있습니다. appDir는 애플리케이션이 실행되는 디렉터리입니다.

  1. 완전한 코드

마지막으로 위의 완전한 기능과 코드를 통합했습니다.

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');

const appDir = 'app';

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      const oldPath = files.file.path;
      const newPath = __dirname + '/' + files.file.name;

      fs.rename(oldPath, newPath, (err) => {
        if (err) throw err;

        console.log('文件上传成功!');
        uncompress(newPath);
      });
    });

    return;
  }

  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end(`
    <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" multiple>
        <button type="submit">上传</button>
    </form>
  `);
}).listen(8080);

console.log('服务器启动成功!');

function compress(file) {
  const gzip = zlib.createGzip();
  const src = fs.createReadStream(file);
  const dest = fs.createWriteStream(file + '.gz');

  src.pipe(gzip).pipe(dest);

  console.log(`文件 ${file} 压缩成功!`);
}

function uncompress(file) {
  const gunzip = zlib.createGunzip();
  const src = fs.createReadStream(file);
  const dest = fs.createWriteStream(file.replace('.gz', ''));

  src.pipe(gunzip).pipe(dest);

  console.log(`文件 ${file} 解压成功!`);
  deploy(file.replace('.gz', ''));
}

function deploy(file) {
  const fileName = path.basename(file);
  const dest = path.join(appDir, fileName);

  fs.copyFile(file, dest, (err) => {
    if (err) throw err;
    console.log(`文件 ${fileName} 部署成功!`);
  });
}

위의 코드는 간단한 파일 업로드, 압축, 압축 풀기 및 배포 기능을 구현하며 필요에 따라 사용자 정의할 수 있습니다.

위 내용은 nodejs 배포 압축 패키지 업로드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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