성능 최적화 예제
여기에는 Sharp 성능 최적화의 예제 및 모범 사례가 제공됩니다.
메모리 최적화
대용량 파일 스트림 처리
javascript
import sharp from 'sharp';
import fs from 'fs';
// 스트림 처리, 전체 파일을 메모리에 로드하지 않음
fs.createReadStream('large-image.jpg')
.pipe(sharp().resize(800, 600))
.pipe(fs.createWriteStream('output.jpg'));파일 대신 Buffer 사용
javascript
// 작은 파일의 경우 Buffer 사용이 더 효율적
const inputBuffer = fs.readFileSync('input.jpg');
const outputBuffer = await sharp(inputBuffer)
.resize(300, 200)
.jpeg({ quality: 80 })
.toBuffer();
fs.writeFileSync('output.jpg', outputBuffer);리소스 즉시 해제
javascript
// 처리 완료 후 즉시 해제
const image = sharp('input.jpg');
await image.resize(300, 200).toFile('output.jpg');
// image 인스턴스는 자동으로 가비지 수집됨동시성 제어
동시성 수 제한
javascript
// 최대 동시성 수 설정
sharp.concurrency(4);
// 일괄 처리 시 동시성 제어
async function batchProcess(files) {
const batchSize = 4;
const results = [];
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
const batchPromises = batch.map(file =>
sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`)
);
await Promise.all(batchPromises);
results.push(...batch);
}
return results;
}큐를 사용한 처리
javascript
class ImageProcessor {
constructor(concurrency = 4) {
this.concurrency = concurrency;
this.queue = [];
this.running = 0;
}
async add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
this.process();
});
}
async process() {
if (this.running >= this.concurrency || this.queue.length === 0) {
return;
}
this.running++;
const { task, resolve, reject } = this.queue.shift();
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.running--;
this.process();
}
}
}
// 사용 예제
const processor = new ImageProcessor(4);
for (const file of files) {
processor.add(async () => {
await sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`);
});
}캐시 최적화
처리 결과 캐싱
javascript
const cache = new Map();
async function processWithCache(inputPath, width, height) {
const key = `${inputPath}_${width}_${height}`;
if (cache.has(key)) {
return cache.get(key);
}
const result = await sharp(inputPath)
.resize(width, height)
.jpeg({ quality: 80 })
.toBuffer();
cache.set(key, result);
return result;
}Sharp 캐시 지우기
javascript
// 메모리 해제를 위해 주기적으로 캐시 지우기
setInterval(() => {
sharp.cache(false);
}, 60000); // 매분마다 지우기알고리즘 선택
적절한 크기 조정 알고리즘 선택
javascript
// 축소 시 더 빠른 알고리즘 사용
await sharp('input.jpg')
.resize(300, 200, { kernel: sharp.kernel.cubic })
.toFile('output.jpg');
// 확대 시 더 고품질 알고리즘 사용
await sharp('input.jpg')
.resize(1200, 800, { kernel: sharp.kernel.lanczos3 })
.toFile('output.jpg');일괄 처리 최적화
javascript
async function optimizedBatchProcess(files) {
// 크기별로 그룹화하여 처리
const smallFiles = [];
const largeFiles = [];
for (const file of files) {
const metadata = await sharp(file).metadata();
if (metadata.width * metadata.height < 1000000) {
smallFiles.push(file);
} else {
largeFiles.push(file);
}
}
// 작은 파일은 빠른 알고리즘 사용
await Promise.all(smallFiles.map(file =>
sharp(file)
.resize(300, 200, { kernel: sharp.kernel.cubic })
.jpeg({ quality: 80 })
.toFile(`output_${file}`)
));
// 큰 파일은 고품질 알고리즘 사용
await Promise.all(largeFiles.map(file =>
sharp(file)
.resize(800, 600, { kernel: sharp.kernel.lanczos3 })
.jpeg({ quality: 90 })
.toFile(`output_${file}`)
));
}네트워크 최적화
스트림 응답
javascript
// Express.js 예제
app.get('/image/:filename', async (req, res) => {
const filename = req.params.filename;
try {
const imageStream = sharp(`images/${filename}`)
.resize(300, 200)
.jpeg({ quality: 80 });
res.set('Content-Type', 'image/jpeg');
imageStream.pipe(res);
} catch (error) {
res.status(404).send('Image not found');
}
});조건부 처리
javascript
app.get('/image/:filename', async (req, res) => {
const { filename } = req.params;
const { width, height, quality = 80 } = req.query;
try {
let image = sharp(`images/${filename}`);
if (width || height) {
image = image.resize(parseInt(width), parseInt(height));
}
if (req.headers.accept?.includes('image/webp')) {
image = image.webp({ quality: parseInt(quality) });
res.set('Content-Type', 'image/webp');
} else {
image = image.jpeg({ quality: parseInt(quality) });
res.set('Content-Type', 'image/jpeg');
}
image.pipe(res);
} catch (error) {
res.status(404).send('Image not found');
}
});모니터링 및 디버깅
성능 모니터링
javascript
async function processWithTiming(inputPath, outputPath) {
const startTime = Date.now();
try {
await sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
const endTime = Date.now();
console.log(`처리 시간: ${endTime - startTime}ms`);
} catch (error) {
console.error('처리 실패:', error.message);
}
}메모리 사용 모니터링
javascript
const process = require('process');
function logMemoryUsage() {
const usage = process.memoryUsage();
console.log('메모리 사용:', {
rss: `${Math.round(usage.rss / 1024 / 1024)} MB`,
heapTotal: `${Math.round(usage.heapTotal / 1024 / 1024)} MB`,
heapUsed: `${Math.round(usage.heapUsed / 1024 / 1024)} MB`,
external: `${Math.round(usage.external / 1024 / 1024)} MB`
});
}
// 처리 전후 메모리 사용 기록
logMemoryUsage();
await sharp('input.jpg').resize(800, 600).toFile('output.jpg');
logMemoryUsage();오류 처리 및 재시도
재시도 메커니즘
javascript
async function processWithRetry(inputPath, outputPath, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
console.log(`처리 성공, 시도 횟수: ${attempt}`);
return;
} catch (error) {
console.error(`시도 ${attempt} 실패:`, error.message);
if (attempt === maxRetries) {
throw new Error(`처리 실패, ${maxRetries}회 재시도함`);
}
// 잠시 대기 후 재시도
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}오류 분류 처리
javascript
async function robustProcess(inputPath, outputPath) {
try {
await sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
} catch (error) {
if (error.code === 'VipsForeignLoad') {
console.error('지원되지 않는 이미지 형식');
} else if (error.code === 'VipsForeignLoadLimit') {
console.error('이미지가 너무 큼, 축소 시도');
// 더 작은 버전 처리 시도
await sharp(inputPath, { limitInputPixels: 268402689 })
.resize(400, 300)
.jpeg({ quality: 80 })
.toFile(outputPath);
} else if (error.code === 'ENOSPC') {
console.error('디스크 공간 부족');
} else {
console.error('알 수 없는 오류:', error.message);
}
}
}모범 사례 요약
1. 적절한 처리 방식 선택
javascript
// 작은 파일: 직접 처리
if (fileSize < 1024 * 1024) {
await sharp(file).resize(300, 200).toFile(output);
}
// 큰 파일: 스트림 처리
else {
fs.createReadStream(file)
.pipe(sharp().resize(300, 200))
.pipe(fs.createWriteStream(output));
}2. 일괄 처리 최적화
javascript
// Promise.all을 사용한 동시 처리
const promises = files.map(file =>
sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`)
);
await Promise.all(promises);3. 메모리 관리
javascript
// 주기적으로 캐시 정리
setInterval(() => {
sharp.cache(false);
}, 300000); // 5분마다 정리4. 오류 처리
javascript
// 항상 try-catch 사용
try {
await sharp(input).resize(300, 200).toFile(output);
} catch (error) {
console.error('처리 실패:', error.message);
// 대체 방안 제공
}