Node.js로 웹서버 생성하고 실행하기

ASHAPPYASIKNOW·2022년 7월 28일
0
post-thumbnail

Node.js로 웹서버 생성하고 실행하기

폴더 생성

D 드라이브에 workspace를 만들고 /nodejs/hello-world 라는 폴더를 만들어준다.

# WSL2 사용 중

> cd /mnt/d/Workspace
> mkdir nodejs
> cd nodejs
> mkdir hello-world
> cd hello-world
> pwd
/mnt/d/Workspace/nodejs/hello-world

hello-world.js 파일 만들기

> touch hello-world.js
> ls
hello-world.js

hello-world.js 파일이 생성된 것을 확인할 수 있다.

hello-world.js

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/plain');
    res.end('Hello, World!\n');
});

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

출처: Node.js v16.16.0 documentation

웹서버 실행하기

WSL2에 아래와 같이 입력하면 서버가 실행된다.

> node hello-world.js
Server running at http://127.0.0.1:3000/


REFERENCES

Node.js v16.16.0 documentation

profile
36.9 It's good time to start something new

0개의 댓글