반응형
Node.js에서 파일 압축을 풀기 위해서는 zlib
모듈이나 unzipper
, adm-zip
등의 라이브러리를 사용할 수 있습니다. 가장 일반적인 사용 사례는 .zip
파일을 여는 것이며, 이를 위해 unzipper
라이브러리를 사용할 수 있습니다. 아래는 unzipper
를 사용해 Node.js에서 .zip
파일을 여는 방법의 예입니다.
1. unzipper
라이브러리 설치
먼저, 프로젝트에 unzipper
라이브러리를 설치해야 합니다:
npm install unzipper
2. .zip
파일 압축 풀기 코드
아래는 특정 디렉터리로 .zip
파일을 압축 해제하는 예제 코드입니다:
const unzipper = require('unzipper');
const fs = require('fs');
const path = require('path');
async function unzipFile(zipFilePath, outputDir) {
// Create the output directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Unzip the file
fs.createReadStream(zipFilePath)
.pipe(unzipper.Extract({ path: outputDir }))
.on('close', () => {
console.log('Unzip completed!');
})
.on('error', (err) => {
console.error('An error occurred:', err);
});
}
// Example usage
const zipFilePath = path.join(__dirname, 'example.zip');
const outputDir = path.join(__dirname, 'output');
unzipFile(zipFilePath, outputDir);
3. 코드 설명
unzipFile
함수는 압축 해제할.zip
파일 경로와 출력 디렉터리를 인자로 받습니다.fs.createReadStream(zipFilePath)
를 통해.zip
파일을 읽어오고,unzipper.Extract
를 사용해 압축을 풉니다.- 압축 해제 작업이 완료되면
close
이벤트가 발생하여 완료 메시지가 출력됩니다.
이 코드는 .zip
파일을 특정 디렉터리에 압축 해제하는 기본적인 방법을 보여줍니다. 더 복잡한 시나리오에서는 파일의 압축을 풀고 파일을 개별적으로 처리하는 등의 추가 작업이 필요할 수 있습니다.
반응형
'언어 > Node.js' 카테고리의 다른 글
[ Node.js ] path.dirname() 파일 경로에서 경로만 가져오기 (0) | 2024.09.05 |
---|---|
[ Node.js ] file 확장자 제외하고 이름만 가져오기 (0) | 2024.09.05 |
[ Node.js ] require() vs import 비교 (0) | 2024.09.04 |
[ Node.js ] CommonJS vs ESM(ECMAScript Module) 비교 (0) | 2024.09.04 |
[ Node.js ] Node.js 버전 역사. (0) | 2024.09.04 |