mime-types는 Node.js에서 많이 쓰이는 MIME 타입 관련 유틸리티 모듈이다 주로 서버에서 파일의 콘텐츠 타입(Content-Type)을 결정할 때 사용한다.
🔍 MIME 타입이란?
MIME 타입(Multipurpose Internet Mail Extensions)은 브라우저나 서버가 파일의 형식을 알 수 있도록 해주는 문자열이다.
간단히, 웹에서의 파일 포맷(확장자)가 정리되어 있는 것이다.
예를 들어:
- .html → text/html
- .jpg → image/jpeg
- .json → application/json
이런 형식으로 파일의 종류를 식별한다.
📦 mime-types 모듈이란?
Node.js의 mime-types는 파일 확장자 ↔ MIME 타입 간 변환을 쉽게 할 수 있도록 도와주는 라이브러리다.
📥 설치
npm install mime-types
✅ 주요 메서드
1. lookup(pathOrExtension)
- 확장자나 파일 이름을 입력하면 MIME 타입을 반환
const mime = require('mime-types');
console.log(mime.lookup('index.html')); // 'text/html'
console.log(mime.lookup('.jpg')); // 'image/jpeg'
2. contentType(extensionOrType)
- MIME 타입 + charset을 포함한 Content-Type 문자열 반환
console.log(mime.contentType('html')); // 'text/html; charset=utf-8'
console.log(mime.contentType('json')); // 'application/json; charset=utf-8'
3. extension(type)
- MIME 타입을 입력하면 파일 확장자를 반환
console.log(mime.extension('text/html')); // 'html'
console.log(mime.extension('application/json')); // 'json'
4. charset(type)
- MIME 타입에 맞는 기본 문자셋(charset)을 반환
console.log(mime.charset('text/html')); // 'UTF-8'
🎯 사용 예: Express 서버에서
const express = require('express');
const mime = require('mime-types');
const fs = require('fs');
const app = express();
app.get('/:file', (req, res) => {
const file = req.params.file;
const type = mime.lookup(file);
if (!type) {
return res.status(404).send('Unknown file type');
}
res.setHeader('Content-Type', type);
fs.createReadStream(file).pipe(res);
});
🔚 요약
기능 메서드 예시
확장자 → MIME 타입 | lookup() | .jpg → image/jpeg |
MIME 타입 → 확장자 | extension() | text/html → html |
Content-Type 생성 | contentType() | html → text/html; charset=utf-8 |
문자셋 추출 | charset() | text/html → UTF-8 |
'BE > Node.js' 카테고리의 다른 글
[ Node.js ] 시작하기 (Express/MongoDB) (0) | 2024.09.10 |
---|