(Node.js) 10줄 정도의 코드로 간단한 웹 서버를 만들 수 있습니다.


Node.js는 빠르고 간단하며 확장 가능한 JavaScript 런타임입니다.

I. 개요

다음은 공식 Node.js 웹 사이트에서 쉽게 찾을 수 있는 약 10줄의 “hello world” 예제입니다. 간단한 코드이지만 동시에 여러 연결을 처리할 수 있습니다.


출처: https://nodejs.org/en/about/

~의

2. 예시

“hello world” 샘플 코드에서 Content-Type을 ‘text/html’로 변경하여 응답을 HTML로 표시합니다.

그리고 “server is running on” 부분이 콘솔 로그에서 제거되었습니다. 그러면 로그창에 표시된 주소를 바로 복사할 수 있어 편리합니다.

const http = require('http');

const hostname="127.0.0.1";
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  res.write('<h1>Hello Node.js</h1>');
  res.write('<h2>Simple and Powerful</h2>');
  res.write('<hr>');  
  res.end();
});

server.listen(port, hostname, () => {
  console.log(`http://${hostname}:${port}/`);
});

결과

> node hello.js
http://127.0.0.1:3000/


~의

3. 리퍼러 URL