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
> touch hello-world.js
> ls
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/