티스토리 뷰

Node.js와 Express.js를 사용해 정적 파일(이미지, CSS, HTML 등)을 서버에서 제공하는 방법을 알아보세요. 간단한 코드 예제와 함께 효율적인 설정 방법을 제공합니다. 초보자도 쉽게 따라할 수 있는 가이드입니다.

 

Node.js는 정적 파일(이미지, CSS, JavaScript 등)을 제공하는 데 매우 유용한 서버 환경입니다. 특히 Express.js와 같은 프레임워크를 활용하면 간단한 코드로 다양한 정적 리소스를 클라이언트에 제공할 수 있습니다. 이 글에서는 Node.js와 Express.js를 사용하여 정적 파일을 읽고 서빙하는 방법을 자세히 설명합니다.

 

Node.js에서 정적 파일이란?

정적 파일은 서버에서 클라이언트로 전달되는 변경되지 않는 리소스를 의미합니다. 예를 들어:

  • HTML 파일: 웹 페이지 구조를 정의
  • CSS 파일: 웹 페이지 스타일링
  • JavaScript 파일: 클라이언트 측 동작 구현
  • 이미지 파일: PNG, JPEG 등

Node.js는 이러한 정적 파일을 효과적으로 처리할 수 있는 여러 방법을 제공합니다.

 

👇👇👇 내용 자세히보기 👇👇👇 

설명 영상 바로가기

Express.js로 정적 파일 서빙하기

기본 설정

Express.js의 express.static 미들웨어는 정적 파일을 서빙하는 가장 간단한 방법입니다. 아래는 기본적인 사용 예제입니다:

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

const app = express();
const PORT = 3000;

// 'public' 폴더를 정적 파일 경로로 설정
app.use(express.static(path.join(__dirname, 'public')));

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

위 코드는 public 폴더에 저장된 모든 정적 파일을 클라이언트가 접근할 수 있도록 만듭니다. 예를 들어 public/images/logo.png에 저장된 이미지는 http://localhost:3000/images/logo.png에서 접근 가능합니다.

다중 디렉토리 설정

다양한 폴더에 저장된 정적 리소스를 관리하려면 여러 번 express.static을 호출할 수 있습니다:

app.use('/images', express.static(path.join(__dirname, 'images')));
app.use('/css', express.static(path.join(__dirname, 'styles')));

이 경우:

  • /images 경로는 images 폴더의 리소스를 제공
  • /css 경로는 styles 폴더의 리소스를 제공

가상 경로 접두사 사용

URL에 실제 디렉토리 이름을 숨기고 싶다면 가상 경로 접두사를 사용할 수 있습니다:

app.use('/static', express.static(path.join(__dirname, 'public')));

이제 http://localhost:3000/static/logo.png와 같은 URL로 public/logo.png에 접근할 수 있습니다.

Node.js 기본 HTTP 모듈로 정적 파일 서빙하기

Express.js 없이도 Node.js의 기본 HTTP 모듈을 사용하여 정적 파일을 서빙할 수 있습니다. 아래는 간단한 예제입니다:

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

const server = http.createServer((req, res) => {
  let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);

  // 확장자 확인 및 Content-Type 설정
  const extname = String(path.extname(filePath)).toLowerCase();
  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'application/javascript',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.gif': 'image/gif',
  };
  const contentType = mimeTypes[extname] || 'application/octet-stream';

  fs.readFile(filePath, (err, content) => {
    if (err) {
      if (err.code === 'ENOENT') {
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end('<h1>404 Not Found</h1>', 'utf-8');
      } else {
        res.writeHead(500);
        res.end(`Server Error: ${err.code}`);
      }
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

이 코드는 요청 URL에 따라 적절한 정적 파일을 반환하며, 없는 경우 404 에러 페이지를 보여줍니다.

Node-static 모듈 사용하기

node-static은 캐싱 기능이 포함된 HTTP 정적 파일 서버 모듈입니다. 설치 후 간단히 사용할 수 있습니다:

npm install node-static

다음은 사용 예제입니다:

const static = require('node-static');
const http = require('http');

const fileServer = new static.Server('./public');

http.createServer((req, res) => {
  fileServer.serve(req, res);
}).listen(3000);

console.log('Server running at http://localhost:3000/');

주요 차이점 비교

방법 장점 단점
Express.js 간편하고 설정이 쉬움 추가 패키지 설치 필요
기본 HTTP 모듈 사용 종속성 없음 코드가 복잡해질 수 있음
node-static 캐싱 및 간단한 설정 지원 추가 패키지 설치 필요

결론

Node.js와 Express.js 또는 기타 도구를 활용하면 정적 파일을 효율적으로 서빙할 수 있습니다. 프로젝트 요구사항에 따라 적합한 방법을 선택하세요. Express.js는 대부분의 경우 가장 간단하고 강력한 솔루션입니다.


자주 묻는 질문

Q1: Express 없이도 정적 파일을 서빙할 수 있나요?
A1: 네, Node.js의 기본 HTTP 모듈만으로도 가능합니다. 하지만 Express를 사용하면 더 간단하고 직관적으로 구현할 수 있습니다.

Q2: 여러 디렉토리에서 정적 파일을 제공하려면 어떻게 하나요?
A2: Express에서는 express.static 미들웨어를 여러 번 호출하여 각 디렉토리를 설정하면 됩니다.

Q3: 캐싱 기능이 필요한 경우 어떤 옵션이 좋나요?
A3: node-static 모듈은 기본적으로 캐싱 기능을 제공합니다. 또는 Express에서도 캐시 관련 옵션을 설정할 수 있습니다.

반응형