Javascript/Node.js

동적 웹페이지 제작, 파일 읽기 기능, 파일을 이용해 본문 구현

leeeee.yeon 2021. 5. 5. 15:28
동적 웹페이지 제작
var http = require('http');
var fs = require('fs');
var url = require('url'); // url이라는 노드는 url이라는 변수를 이용하여 사용할 것이다.
var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var title=queryData.id;
    console.log(queryData.id);
    if(_url == '/'){
      title = 'Welcome';
    }
    if(_url == '/favicon.ico'){
        response.writeHead(404);
        response.end();
        return;
    }
    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>
      <ol>
        <li><a href="/?id=HTML">HTML</a></li>
        <li><a href="/?id=CSS">CSS</a></li>
        <li><a href="/?id=JavaScript">JavaScript</a></li>
      </ol>
      <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);

main.js를 위와 같이 수정한다.

  • template 변수 만든 뒤, 1.html 내용 복붙
  • title 변수 만든 뒤, title=queryData.id
  • title과 h2 부분에 ${title} 입력
  • respond.end()의 인자를 template으로 변경
  • WEB(메인)을 클릭했을 때 주소를 "/"로 변경
  • 9~11번째 줄과 같이 조건문 수정 > WEB 클릭했을 시 title을 Welcome으로 변경

결과

 

파일 읽기 기능

 

CRUD:

Create

Read

Update

Delete

 

중 Read에 대해 해볼 것이다.

 

연습을 위해 nodejs 폴더를 만들고 그 안에 fileread.js와 sample.txt 파일을 만들자.

//fileread.js

var fs = require('fs');
fs.readFile('sample.txt', 'utf8', function(err, data){
    console.log(data);
});
// sample.txt
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.

우리는 터미널에서 Node.js 디렉토리 상에 있으니 터미널에 cd nodejs라고 입력하여 nodejs 폴더로 들어온 뒤, node fileread.js를 입력하여 실행하면

이렇게 파일 속 내용을 읽을 수 있다.

 

파일을 이용해 본문 구현

data 디렉토리를 만들고 그 안에 HTML, CSS, JavaScript 파일을 만들어 본문 내용을 복붙한다.

그리고 main.js를 아래와 같이 수정한다.

var http = require('http');
var fs = require('fs');
var url = require('url'); // url이라는 노드는 url이라는 변수를 이용하여 사용할 것이다.
var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var title=queryData.id;
    console.log(queryData.id);
    if(_url == '/'){
      title = 'Welcome';
    }
    if(_url == '/favicon.ico'){
        response.writeHead(404);
        response.end();
        return;
    }
    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>
      <ol>
        <li><a href="/?id=HTML">HTML</a></li>
        <li><a href="/?id=CSS">CSS</a></li>
        <li><a href="/?id=JavaScript">JavaScript</a></li>
      </ol>
      <h2>${title}</h2>
      <p>${description}</p>
    </body>
    </html>
    `
    response.end(template);
    })
 
});
app.listen(3000);
  • fs.readFile() 함수 추가
  • 주의 !! response.end(template);이 fs.readFile() 함수 안에 있음