SHIN STORYSHIN STORY
홈포스트C#TypeScriptNext.jsNode.js시리즈
</>SHIN STORY

sdf

탐색

  • 홈
  • 모든 포스트
  • 시리즈
  • 검색

카테고리

  • C#
  • TypeScript
  • Next.js
  • Node.js
  • 알고리즘
  • 개발 도구

© 2025 Shin Blog. All rights reserved.

GitHubRSS
목록으로
Node.js#JavaScript#Node.js#Backend

Node.js HTTP 서버 직접 구현하기

SHIN

2026년 5월 2일2분 읽기0
📚

Node.js 실전 팁 20선

20편
  1. 3Node.js Stream으로 대용량 파일 처리하기
  2. 4Worker Threads로 CPU 집약 작업 처리하기
  3. 5cluster 모듈로 멀티코어 CPU 100% 활용하기
  4. 6child_process로 외부 명령 실행하기
  5. 7fs/promises로 파일 시스템 다루기
  6. 20Node.js Event Loop 완전 정복
  7. 20Node.js path 모듈 완전 정복
  8. 20환경 변수 관리 — .env, dotenv, 그리고 검증
  9. 20EventEmitter 패턴으로 느슨한 결합 구현하기
  10. 20Node.js crypto 모듈로 해싱과 암호화 구현하기
  11. 20Node.js 메모리 누수 찾고 수정하기
  12. 20Express 미들웨어 패턴과 에러 처리
  13. 20Node.js CJS vs ESM 모듈 시스템 완전 정리
  14. 20Node.js Buffer와 인코딩 완전 가이드
  15. 20PM2로 Node.js 프로세스 관리하기
  16. Node.js HTTP 서버 직접 구현하기현재
  17. 20Node.js 성능 프로파일링 실전 가이드
  18. 20Node.js npm 스크립트 완전 활용하기
  19. 20Node.js 보안 체크리스트 10가지
  20. 20Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

Node.js HTTP 서버 직접 구현하기

Express 같은 프레임워크의 내부를 이해하려면 내장 http 모듈부터 시작해야 합니다.

기본 HTTP 서버

CODE
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Hello, World!' }));
});

server.listen(3000, () => {
  console.log('서버 실행 중: http://localhost:3000');
});

라우터 구현

CODE
const http = require('http');
const { URL } = require('url');

const routes = new Map();

function addRoute(method, path, handler) {
  routes.set(`${method.toUpperCase()}:${path}`, handler);
}

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const handler = routes.get(`${req.method}:${url.pathname}`);

  res.setHeader('Content-Type', 'application/json');

  if (!handler) {
    res.writeHead(404);
    return res.end(JSON.stringify({ error: 'Not Found' }));
  }

  try {
    await handler(req, res, url);
  } catch (err) {
    res.writeHead(500);
    res.end(JSON.stringify({ error: err.message }));
  }
});

// 라우트 등록
addRoute('GET', '/health', (req, res) => {
  res.writeHead(200);
  res.end(JSON.stringify({ status: 'ok' }));
});

addRoute('GET', '/users', async (req, res) => {
  const users = await db.findAll();
  res.writeHead(200);
  res.end(JSON.stringify(users));
});

요청 본문 파싱

CODE
function parseBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => {
      const body = Buffer.concat(chunks).toString();
      try {
        resolve(JSON.parse(body));
      } catch {
        resolve(body);
      }
    });
    req.on('error', reject);
  });
}

addRoute('POST', '/users', async (req, res) => {
  const body = await parseBody(req);
  const user = await db.create(body);
  res.writeHead(201);
  res.end(JSON.stringify(user));
});

HTTPS 서버

CODE
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
};

https.createServer(options, (req, res) => {
  res.end('HTTPS OK');
}).listen(443);

Keep-Alive와 타임아웃

CODE
const server = http.createServer(handler);

server.keepAliveTimeout = 65_000;   // 65초
server.headersTimeout = 66_000;     // keepAlive보다 약간 길게

// 요청 처리 타임아웃
server.setTimeout(30_000, (socket) => {
  socket.destroy(); // 30초 초과 연결 강제 종료
});
공유
S

SHIN

.NET 개발자입니다

GitHub
PM2로 Node.js 프로세스 관리하기

이전 포스트

PM2로 Node.js 프로세스 관리하기

다음 포스트

Node.js 성능 프로파일링 실전 가이드

Node.js 성능 프로파일링 실전 가이드

같은 카테고리 포스트

Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

Node.js 테스팅 전략 — 단위, 통합, E2E 테스트

2026년 5월 6일· 2분
Node.js 보안 체크리스트 10가지

Node.js 보안 체크리스트 10가지

2026년 5월 5일· 2분
Node.js npm 스크립트 완전 활용하기

Node.js npm 스크립트 완전 활용하기

2026년 5월 4일· 1분

댓글