WEB Front-End/Node.js

Node.js 서버 메모장

hyg4196 2021. 11. 29. 17:56
반응형
const http = require('http');
const fs = require('fs').promises; // 프로미스 기반 fs 를 사용하려면 .promises 를 붙여야 됌, 안그럼 오류남

const server = http.createServer(function(req, res){
    new Promise(function(resolve, reject){
        var data = fs.readFile('./index.html');
        resolve(data);
    }).then(function(result){
    // 서버 응답
        var data = result;
        res.writeHead(200, {'Content-type' : 'text/html; charset=utf-8'}); // 200 은 성공을 의미
        res.end(data);
    }).catch(function(reject){
        console.log(reject);
    });;
    
}).listen(8080, function(){
    // 서버 연결
    console.log('서버2 자동실행 !');
    startServer02();
});

server.on('error', (error) => {
    // 에러 출력
    console.log (error);
});

/**
 *  HTTP 상태 코드
 * 
 *  2xx : 성공을 알리는 상태 200 : 성공, 201 : 작성됌
 *  3xx : 리다이렉션 상태    301 : 영구이동 , 302 : 임시 이동
 *  4xx : 요청 오류          400 : 잘못된 요청 , 403 : 금지됌 , 404 : 찾을 수 없음
 *  5xx : 서버 오류          500 : 내부 서버 오류 , 502 : 불량 게이트웨이 , 503 : 서비스를 사용 x
 *  
 */

// 2번 서버
function startServer02(){
    const server2 = http.createServer(function(req, res){
        res.writeHead(200, {'Content-type' : 'text/html; charset=utf-8'});
        res.write('<h1> hello node server 2!</h1>');
        res.end('<p> hello server 2! </p>');
    }).listen(8081, function(){
        console.log('서버1, 서버2 대기중');
    });

    server2.on('error', (error) => {
        console.log(error);
    });
}
반응형