본문 바로가기

Back-End/Node.js

Node.js.13. App 제작 - 파일을 이용해 본문 구현

반응형

목표

Query string 값에 따라 본문이 변경되는 웹 애플리케이션 만들기

 


글자를 클릭할 때마다 해당 파일의 본문이 나오도록 하기 위해 data 폴더 안에 HTML, CSS, JavaScript 파일을 각각 만든다.

//CSS
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language. Although most often used to set the visual style of web pages and user interfaces written in HTML and XHTML, the language can be applied to any XML document, including plain XML, SVG and XUL, and is applicable to rendering in speech, or on other media. Along with HTML and JavaScript, CSS is a cornerstone technology used by most websites to create visually engaging webpages, user interfaces for web applications, and user interfaces for many mobile applications.

//HTML
<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.
</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.


//JavaScript
JavaScript (/ˈdʒɑːvəˌskrɪpt/[6]), often abbreviated as JS, is a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language. Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production. It is used to make webpages interactive and provide online programs, including video games. The majority of websites employ it, and all modern web browsers support it without the need for plug-ins by means of a built-in JavaScript engine. Each of the many JavaScript engines represent a different implementation of JavaScript, all based on the ECMAScript specification, with some engines not supporting the spec fully, and with many engines supporting additional features beyond ECMA.

 

파일을 읽기 위해 모듈 fs를 불러오고 fs.readFile()를 이용해 파일을 불러온다.

    fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){

본문을 description으로 지정하고, 속에는 화면에 띄울 내용을 작성해준다.

// main.js
var http = require('http');
var url = require('url');
var fs = require('fs');

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);
    //query string에 따라서 파일명이 생성됨
    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);

 

이제 Nodejs를 껐다켜지 않아도 바로 페이지가 반영된다. 왜냐하면 페이지가 열릴 때마다 HTML파일의 내용을 읽어서 출력해주기 때문이다.

즉, main.js 안에 있는 내용은 실행할 때마다 내용을 읽기 때문에 내용이 수정될 때마다 실시간으로 바뀌는 것이다.

반응형