Node.js란?

Node.js는 자바스크립트 엔진 ‘V8’ 위에서 동작하는 이벤트 처리 I/O 프레임워크이다. 서버 환경에서 자바스크립트로 애플리케이션을 작성할 수 있도록 도와준다.


스크린샷 2021-01-29 오전 1 55 52


Node.js 특징

정의: 크롬 V8 자바스크립트 엔진으로 빌드된 자바스크립트 런타임 특징: 이벤트 기반, 논블로킹 I/O 모델을 사용해 가볍고 효율적 이벤트 기반: 이벤트가 발생할 때 미리 지정해둔 작업을 수행하는 방식을 의미 논블로킹 I/O: 논블로킹이란 이전 작업이 완료될 때까지 멈추지 않고 다음 작업을 수행함을 뜻하며 현재 노드 프로세스 외의 다른 컴퓨팅 자원을 사용할 수 있는 I/O(입출력) 작업이 시간적 이득을 많이 얻음



Node.js - 웹서버 만들기

  • 소스코드가 변경되면 Node.js를 껐다가 다시 켜줘야 코드가 반영된다.
var http = require("http");
var fs = require("fs");
var app = http.createServer(function (request, response) {
  var url = request.url;
  if (request.url == "/") {
    url = "/index.html";
  }
  if (request.url == "/favicon.ico") {
    response.writeHead(404);
    response.end();
    return;
  }
  response.writeHead(200);
  response.end(fs.readFileSync(__dirname + url));
});
app.listen(3000);

어떤코드를 넣냐에 따라 사용자에게 전송하는 데이터가 바뀐다. Node.js같은 것들은 할 수 있다. 사용자에게 전송할 데이터를 생성한다. 라는것이 Node.js가 가진 힘이다.



Node.js - URL로 입력된 값 사용하기

스크린샷 2021-01-29 오전 2 08 58

query string의 시작은 ?로 하기로 약속 되어있고, 값의 이름과 값은 =로 구분되도록 약속 되어있다. query string값에 따라서 node.js를 통해 만든 웹 서버가 사용자에게 동적으로 생성된 정보를 전송할수 있다.

var http = require("http");
var fs = require("fs");
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  console.log(queryData.id);
  if (_url == "/") {
    _url = "/index.html";
  }
  if (_url == "/favicon.ico") {
    response.writeHead(404);
    response.end();
    return;
  }
  response.writeHead(200);
  response.end(queryData.id);
});
app.listen(3000);

queryData에 담겨있는 정보는 객체이다. 위와 같이 코드를 이용하면 query string에 따라서 그 정보가 나오게 가능하다.



Node.js - 동적인 웹페이지 만들기

var http = require("http");
var fs = require("fs");
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var title = queryData.id;
  if (_url == "/") {
    title = "Welcome";
  }
  if (_url == "/favicon.ico") {
    return response.writeHead(404);
  }
  response.writeHead(200);
  var template = `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${title}</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      <ul>
        <li><a href="/?id=HTML">HTML</a></li>
        <li><a href="/?id=CSS">CSS</a></li>
        <li><a href="/?id=JavaScript">JavaScript</a></li>
      </ul>
      <h2>${title}</h2>
      <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
      <img src="coding.jpg" width="100%">
      </p><p style="margin-top:45px;">HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets.
      </p>
    </body>
    </html>
    `;
  response.end(template);
});
app.listen(3000);

var title = queryData.id; ${title} 을 통해서 queryData.id가 변할 때 즉 query string값이 변할 때 동적으로 데이터가 변하게 해준다.



Node.js - 파일 읽기

var fs = require("fs");
fs.readFile("sample.txt", "utf8", function (err, data) {
  console.log(data);
});

fileread.js 파일을 만들어주고 sample.txt 파일을 만들어 준다. 위와 같이 코드를 이용하면 sample.txt 파일을 읽어준다. ‘utf8’ 를 추가하여 한글로 읽어져 우리한테 표현될 수 있게 해준다.



Node.js - 파일을 이용해 본문 구현

var http = require("http");
var fs = require("fs");
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var title = queryData.id;
  if (_url == "/") {
    title = "Welcome";
  }
  if (_url == "/favicon.ico") {
    return response.writeHead(404);
  }
  response.writeHead(200);
  fs.readFile(`data/${queryData.id}`, "utf8", function (err, description) {
    var template = `
      <!doctype html>
      <html>
      <head>
        <title>WEB1 - ${title}</title>
        <meta charset="utf-8">
      </head>
      <body>
        <h1><a href="/">WEB</a></h1>
        <ul>
          <li><a href="/?id=HTML">HTML</a></li>
          <li><a href="/?id=CSS">CSS</a></li>
          <li><a href="/?id=JavaScript">JavaScript</a></li>
        </ul>
        <h2>${title}</h2>
        <p>${description}</p>
      </body>
      </html>
      `;
    response.end(template);
  });
});
app.listen(3000);

data 파일을 만들어 HTML,CSS,Javascript 관련 내용이 들어가 있는 각각의 순수한 본문만을 가지고 있는 정보 파일들을 만들어 넣어준다 이어 fs.readFile(data/${queryData.id}, ‘utf8’, function(err, description) 코드를 통하여 query string에 따라 data 파일에 있는 각각의 정보들을 가져와 준다.



Node.js - 콘솔에서의 입력값

var args = process.argv;
console.log(args[2]);
console.log("A");
console.log("B");
if (args[2] === "1") {
  console.log("C1");
} else {
  console.log("C2");
}
console.log("D");

콘솔을 통해 입력을 하고 그에 관한 값들 출력



Node.js - Not found 오류 구현

var http = require("http");
var fs = require("fs");
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var pathname = url.parse(_url, true).pathname;
  var title = queryData.id;

  if (pathname === "/") {
    fs.readFile(`data/${queryData.id}`, "utf8", function (err, description) {
      var template = `
        <!doctype html>
        <html>
        <head>
          <title>WEB1 - ${title}</title>
          <meta charset="utf-8">
        </head>
        <body>
          <h1><a href="/">WEB</a></h1>
          <ul>
            <li><a href="/?id=HTML">HTML</a></li>
            <li><a href="/?id=CSS">CSS</a></li>
            <li><a href="/?id=JavaScript">JavaScript</a></li>
          </ul>
          <h2>${title}</h2>
          <p>${description}</p>
        </body>
        </html>
        `;
      response.writeHead(200);
      response.end(template);
    });
  } else {
    response.writeHead(404);
    response.end("Not found");
  }
});
app.listen(3000);

조건문을 통해서 query string값이 존재하지 않는 값일 때, Not found가 나오게 해준다.



Node.js - 홈페이지 구현

var http = require("http");
var fs = require("fs");
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var pathname = url.parse(_url, true).pathname;
  if (pathname === "/") {
    if (queryData.id === undefined) {
      fs.readFile(`data/${queryData.id}`, "utf8", function (err, description) {
        var title = "Welcome";
        var description = "Hello, Node.js";
        var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ul>
              <li><a href="/?id=HTML">HTML</a></li>
              <li><a href="/?id=CSS">CSS</a></li>
              <li><a href="/?id=JavaScript">JavaScript</a></li>
            </ul>
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readFile(`data/${queryData.id}`, "utf8", function (err, description) {
        var title = queryData.id;
        var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ul>
              <li><a href="/?id=HTML">HTML</a></li>
              <li><a href="/?id=CSS">CSS</a></li>
              <li><a href="/?id=JavaScript">JavaScript</a></li>
            </ul>
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;
        response.writeHead(200);
        response.end(template);
      });
    }
  } else {
    response.writeHead(404);
    response.end("Not found");
  }
});
app.listen(3000);

if(queryData.id === undefined) 일때 와 아닐때를 구별하여 개발



Node.js - 파일 목록 알아내기

var testFolder = "./data";
var fs = require("fs");

fs.readdir(testFolder, function (error, filelist) {
  console.log(filelist);
});

data 파일에 있는 파일들을 읽고 목록을 출력 -> 이때 배열 형식으로 목록이 나타남



Node.js - 글목록 출력하기

var http = require("http");
var fs = require("fs");
var url = require("url");

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var pathname = url.parse(_url, true).pathname;
  if (pathname === "/") {
    if (queryData.id === undefined) {
      fs.readdir("./data", function (error, filelist) {
        var title = "Welcome";
        var description = "Hello, Node.js";
        var list = "<ul>";
        var i = 0;
        while (i < filelist.length) {
          list =
            list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
          i = i + 1;
        }
        list = list + "</ul>";
        var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            ${list}
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir("./data", function (error, filelist) {
        var title = "Welcome";
        var description = "Hello, Node.js";
        var list = "<ul>";
        var i = 0;
        while (i < filelist.length) {
          list =
            list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
          i = i + 1;
        }
        list = list + "</ul>";
        fs.readFile(
          `data/${queryData.id}`,
          "utf8",
          function (err, description) {
            var title = queryData.id;
            var template = `
            <!doctype html>
            <html>
            <head>
              <title>WEB1 - ${title}</title>
              <meta charset="utf-8">
            </head>
            <body>
              <h1><a href="/">WEB</a></h1>
              ${list}
              <h2>${title}</h2>
              <p>${description}</p>
            </body>
            </html>
            `;
            response.writeHead(200);
            response.end(template);
          }
        );
      });
    }
  } else {
    response.writeHead(404);
    response.end("Not found");
  }
});
app.listen(3000);

위에서 파일 목록 읽기를 통하여 filelist를 이용하여 좀더 효율적으로 홈페이지 구현


var list = "<ul>";
var i = 0;
while (i < filelist.length) {
  list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
  i = i + 1;
}
list = list + "</ul>";

파일 목록 출력을 이용하여 배열로 나타나는 것을 이용, 이를 이용하여 반복문을 이용하여 각 CSS,HTML,JavaScript 파일들을 따로따로 코드작성을 안하고 한번에 값을 받음



Node.js - 함수를 이용해서 정리 정돈하기

var http = require("http");
var fs = require("fs");
var url = require("url");

function templateHTML(title, list, body) {
  return `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    ${body}
  </body>
  </html>
  `;
}
function templateList(filelist) {
  var list = "<ul>";
  var i = 0;
  while (i < filelist.length) {
    list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
    i = i + 1;
  }
  list = list + "</ul>";
  return list;
}

var app = http.createServer(function (request, response) {
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  var pathname = url.parse(_url, true).pathname;
  if (pathname === "/") {
    if (queryData.id === undefined) {
      fs.readdir("./data", function (error, filelist) {
        var title = "Welcome";
        var description = "Hello, Node.js";
        var list = templateList(filelist);
        var template = templateHTML(
          title,
          list,
          `<h2>${title}</h2>${description}`
        );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir("./data", function (error, filelist) {
        fs.readFile(
          `data/${queryData.id}`,
          "utf8",
          function (err, description) {
            var title = queryData.id;
            var list = templateList(filelist);
            var template = templateHTML(
              title,
              list,
              `<h2>${title}</h2>${description}`
            );
            response.writeHead(200);
            response.end(template);
          }
        );
      });
    }
  } else {
    response.writeHead(404);
    response.end("Not found");
  }
});
app.listen(3000);

위의 중복된 코드들을 함수로 정리함으로써 좀 더 효율적이고 보기 좋은 코드로 만듬.



공부 진행중….