반응형

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
	Hello World
</body>
</html>

server.js

import fs from 'fs';
import http from 'http';

http.createServer((request, response) => {
    console.log(`request url : ${request.url}`);

    try {
        if (request.url === '/favicon.ico') {
            return response.writeHead(404);
        }

        const url = request.url === '/' ? '/index.html' : request.url;

        response.writeHead(200);
        response.end(fs.readFileSync(__dirname + url));
    } catch (e) {
        console.error(e);
        response.writeHead(500);
        response.end('Error');
    }
}).listen(8080);

package.json

{
    "scripts": {
        "start": "babel-node server.js"
    },
    "devDependencies": {
        "babel-cli": "^6.26.0",
        "babel-node": "^0.0.1-security",
        "babel-preset-env": "^1.7.0"
    },
    "babel": {
        "presets": [
            "env"
        ]
    }
}

설치 및 시작

yarn install
yarn start

참고

반응형

'Development > NodeJS' 카테고리의 다른 글

[NodeJS] Koa Framework 예제  (0) 2020.12.29
[NodeJS] Custom Module 사용하기  (0) 2020.12.29
[NodeJS] Javascript를 Shell Script처럼 실행하기  (0) 2020.12.29
[NodeJS] prettier, eslint 설정  (0) 2020.12.29
[NodeJS] Node 설치하기  (0) 2020.12.29

+ Recent posts