오늘은 파일의 내용을 읽는 자바스크립트를 작성해보겠습니다.

 

 

파일시스템 모듈 가져오기

파일의 내용을 읽으려면 파일시스템 모듈을 가져와야 합니다. 파일시스템 모듈을 가져오기 위해선 밑에 코드 한줄이면 됩니다.

var fs = require('fs');

 

이러면 이제 변수 fs는 파일시스템 모듈을 사용할 수 있게됩니다.

 

그렇다면 이제 fs를 이용하여 파일을 읽어오는 명령어를 입력하겠습니다.

fs.readFile('sample.txt', 'utf-8',function(err, data) {
  console.log(data);
});

 

readFile을 분석해보겠습니다.

 

readFile('파일 경로', '옵션', '함수기능') -> 이렇게 구성되어있습니다.

 

  • sample.txt : 파일 경로
  • utf-8 : 파일을 출력할 때 방식
  • function(err, dada) : 자세히는 모르지만.. 기능을 나열 하는 것 같음, 그리고 파일의 내용을 data변수에 저장
  • console.log(data) : data변수에 저장된 값을 출력

 

 

동적인 웹페이지에 적용

동적인 웹페이지에 적용하기 위해서는 전에 만들었던 예제 파일을 불러옵니다.

var http = require('http');
var fs = require('fs');
var urlmodule = require('url');
var app = http.createServer(function(request,response){
    var url = request.url;
    var queryData = urlmodule.parse(url, true).query;
    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>
  <ol>
    <li><a href="1.html">HTML</a></li>
    <li><a href="2.html">CSS</a></li>
    <li><a href="3.html">JavaScript</a></li>
  </ol>
  <h2>${title}</h2>
  <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
  </p>
</body>
</html>
`;
      if(url == '/'){
        url = '/index.html';
      }
      if(url == '/favicon.ico'){
          response.writeHead(404);
          response.end();
          return;        
      }
      response.writeHead(200);
      response.end(template);
 
});
app.listen(3000);

 

여기서 <h2>${title}</h2> 밑에 있는 <p>부분을 변수로 대체할 예정입니다. 밑에 파일을 다운받아 data폴더를 만든 후 안에 집어넣어주세요.

HTML
0.00MB
CSS
0.00MB

 

JavaScript
0.00MB

 

이제 이 파일들의 내용을 불러올겁니다. 위에서 배운 readFile을 이용합니다.

fs.readFile(`../data/${title}`, 'utf-8' function (err, data){});

 

그레이브악센트 안에있는 ../data/${title}은 경로를 얘기합니다. 저는 main.js 위의 폴더에 data폴더가 있기 때문에 저렇게 썼지만, 개인마다 다를 수 있으니 꼭 자신의 data 폴더의 경로를 확인해주세요.

 

${title}은 위의 코드에서 보면 queryData.id가 저장되어있습니다. queryData.id를 HTML, CSS, JavaScript로 입력해주면 동적인 웹페이지를 띄울 수 있게됩니다.

 

마지막으로 중괄호{} 안에는 페이지를 웹브라우저에 띄우는 모든 코드를 긁어오셔야 합니다. 밑에 코드가 페이지를 띄우는 코드입니다.

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="1.html">HTML</a></li>
    <li><a href="2.html">CSS</a></li>
    <li><a href="3.html">JavaScript</a></li>
  </ol>
  <h2>${title}</h2>
  <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
</body>
</html>
`;
if(url == '/'){
  url = '/index.html';
}
if(url == '/favicon.ico'){
  response.writeHead(404);
  response.end();
  return;        
}
      response.writeHead(200);
      response.end(template);

여기서 <p>부분을 동적으로 표현하기위해 변수를 써줍니다. ${data}변수가 내용을 담고있으므로 ${data}변수로 대체합니다.

 

대체한 코드를 다시 적어보면 이렇게 됩니다.

    fs.readFile(`../data/${title}`, 'utf-8', function(err, data) {
      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="1.html">HTML</a></li>
            <li><a href="2.html">CSS</a></li>
            <li><a href="3.html">JavaScript</a></li>
          </ol>
          <h2>${title}</h2>
          ${data}
        </body>
        </html>
      `;
      if(url == '/'){
        url = '/index.html';
      }
      if(url == '/favicon.ico'){
          response.writeHead(404);
          response.end();
          return;        
      }
      response.writeHead(200);
      response.end(template);
    });

 

이제 서버를 키고 주소창에 "localhost:3000/?id=HTML"을 입력합니다. 쿼리스트링 값을 id=CSS, id=JavaScript로 바꿔가며 확인해봅니다. 아래와 같은 결과를 얻을 수 있습니다.

 

 

 

마무리

이상으로 queryString 값에 따라 동적으로 페이지가 변하는 모습을 확인해보았습니다.