Node.js 기반 웹 서버 구축 방법

Node.js는 JavaScript를 사용하여 서버 측 애플리케이션을 구축할 수 있는 플랫폼입니다. 이번 글에서는 Node.js를 사용하여 간단한 웹 서버를 구축하는 방법에 대해 알아보겠습니다.

1. Node.js 설치

먼저, Node.js를 설치해야 합니다. Node.js 공식 웹사이트(https://nodejs.org)에서 다운로드하여 설치할 수 있습니다. 설치가 완료되면 터미널 또는 명령 프롬프트에서 node --version 명령어를 실행하여 정상적으로 설치되었는지 확인할 수 있습니다.

2. 웹 서버 생성

Node.js에서 기본적으로 제공하는 http 모듈을 사용하여 웹 서버를 생성할 수 있습니다. 다음은 간단한 예제 코드입니다:

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!');
});

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

위 코드를 server.js 파일에 저장한 뒤 터미널 또는 명령 프롬프트에서 node server.js 명령어로 서버를 실행할 수 있습니다. 이제 웹 브라우저에서 http://localhost:3000 주소로 접속하면 “Hello, World!” 메시지가 표시됩니다.

3. 정적 파일 서비스

위 예제는 간단한 텍스트를 반환하는 웹 서버이지만, 정적 파일을 제공하는 웹 서버로 확장할 수도 있습니다. 다음은 정적 파일 서비스를 추가한 예제 코드입니다:

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

const server = http.createServer((req, res) => {
  const filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);
  const contentType = getContentType(filePath) || 'text/plain';
  const readStream = fs.createReadStream(filePath);

  readStream.pipe(res);
});

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

function getContentType(filePath) {
  const extname = path.extname(filePath);
  switch (extname) {
    case '.html':
      return 'text/html';
    case '.css':
      return 'text/css';
    case '.js':
      return 'text/javascript';
    default:
      return null;
  }
}

위 코드는 public 폴더에 있는 정적 파일들을 서비스합니다. 예를 들어 public 폴더에 index.html, styles.css, script.js 파일이 있다면 웹 브라우저에서 http://localhost:3000, http://localhost:3000/styles.css, http://localhost:3000/script.js 등의 주소로 접속할 수 있습니다.

마무리

Node.js를 사용하여 간단한 웹 서버를 구축하는 방법에 대해 알아보았습니다. 위 예제 코드를 기반으로 다양한 기능을 추가하며 웹 서버를 보다 유연하고 강력하게 구축할 수 있습니다. Node.js는 널리 사용되는 웹 개발 플랫폼이므로, 충분한 학습 자료와 커뮤니티 지원을 받을 수 있습니다.

자세한 내용은 Node.js 공식 문서를 참고하시기 바랍니다.

#Node.js #웹서버