반응형

 

 

1. Node.js 다운로드

https://nodejs.org/ko/download

 

위에 사이트에 접속해서 Node.js를 다운로드 및 설치를 진행한다.

(2025-04-05 기준)

Windows 키 > Powershell 입력 후 아래의 명령어를 입력한다.

# fnm 다운로드 및 설치:
winget install Schniz.fnm

 

이후 다시 Powershell을 열고, 아래의 명령어를 입력한다.

# Node.js 다운로드 및 설치:
fnm install 22

# Node.js 버전 확인:
node -v # "v22.14.0"가 출력되어야 합니다.

npm 버전 확인:
npm -v # 10.9.2가 출력되어야 합니다.

(npm -v가 아무것도 안 뜬다면, 명령프롬프트로 들어가서 npm -v로 입력해볼 것)

 

 

2. 샘플 페이지 생성

1) npm init 합니다.

< Windows의 경우 >

mkdir example
chdir example
npm init -y

(위를 따르기 싫다면, 아무 폴더를 생성하고, 명령프롬프트로 연 다음. 그 폴더로 이동한 후,

npm init -y 명령어를 입력하면 된다.)

 

 

2) 샘플 Server 페이지 만듭니다. (server.js)

// Import the required modules
const http = require('http');

// Create the HTTP server
const server = http.createServer((req, res) => {
  // Set the response header
  res.writeHead(200, {'Content-Type': 'text/html'});
  
  // Send the response body
  res.end(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Node.js Example</title>
      <style>
        body {
          font-family: Arial, sans-serif;
          text-align: center;
          margin-top: 50px;
          background-color: #f0f0f0;
        }
        h1 {
          color: #333;
        }
      </style>
    </head>
    <body>
      <h1>Hello from Node.js!</h1>
      <p>This is a simple web page served by a Node.js HTTP server.</p>
      <p>Current time: ${new Date().toLocaleTimeString()}</p>
    </body>
    </html>
  `);
});

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

 

 

3) 서버를 실행합니다.

node server.js

 

4) 페이지에 접속해봅니다.

웹브라우저를 실행하여 아래의 주소로 들어가봅니다.

http://localhost:3000

 

 

아래의 접속화면이 뜨면 정상입니다.

 

 

 

추가 구성: Express.js를 활용해 test 페이지 생성 방법

Express.js는 Node.js 서버 구성 시 흔하게 쓰이는 프레임워크입니다. Express.js는 웹 개발 시 빠르게, 그리고 유지개발을 쉽게 해줍니다.

이 프레임워크를 활용하여, 테스트 페이지를 출력해보겠습니다.

1) Express 설치

npm install express

 

2) 샘플 Server 페이지 만듭니다. (server.js)

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

// Serve static files from a 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

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

 

3) server.js 파일이 있는 위치에 public 디렉토리를 만들고, 그 안에 index.html을 만듭니다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Express Example</title>
  <link rel="stylesheet" href="/styles.css">
</head>
<body>
  <h1>Welcome to Express</h1>
  <p>This page is served using Express.js</p>
</body>
</html>

 

4) 서버를 실행하고 테스트 페이지를 확인해봅니다.

node server.js

 

http://localhost:3000

 

 

아래의 접속화면이 뜨면 정상입니다.

 

반응형