data directory 에 파일이 추가되거나 수정되고 삭제되는 것을 Node.js를 통해 어떻게 알아낼 수 있는가?

"Node.js file list in directory" 검색 후 결과 중 아래 링크 참고 ( "fs.readdir")

https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j

 

How do you get a list of the names of all files present in a directory in Node.js?

I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

stackoverflow.com

위 링크에 나온 코드 이용하여 공부!

 

// nodejs 폴더에 readdir.js 파일 생성

var testFolder = './data';
var fs = require('fs');
 
fs.readdir(testFolder, function(error, filelist){
  console.log(filelist);
})

 

./data 

실행하는 위치를 기준으로 'data'라는 directory의 경로를 testFoler에 저장

(./ : 현재 directory)

 

글목록 출력하기 

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 배열의 개수(길이)만큼 while 반복문이 실행된다. 

현재 data directory 내에는 CSS,HTML,JavaScript라는 파일이 존재하는데, 만약 내가 directory 안에 file1,file2 라는 파일을 추가로 생성한다면 웹 페이지에는 CSS,HTML,JavaScript,file1,file2 라는 이름을 가진 링크가 출력된다. 

 

<기존 코드>

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);

pathname이라는 값을 통해서는 Home 과 각각의 페이지를 구분할 수 없음

반복문을 중첩해서 사용함으로써 구분!

JavaScript 에서는 없는 값을 호출 할 때, "undefined "라 부름

if(queryData.id === undefined){	//HOME

}else{	//각 페이지

}

 

<전체 코드>

 

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);
response.writeHead(200);
response.end(template);

위 코드는 if (pathname === '/'){ ... } 안에 있는 코드이고

else 부분에는 다음의 코드를 넣는다. 

response.writeHead(404);
response.end('Not Found');

200 : 200이라는 숫자를 서버가 브라우저에게 주면 "파일을 성공적으로 전송함"

404 : 파일을 찾을 수 없는 경우, 웹 서버는 404라는 약속된 번호를 준다. 

 

<전체 코드>

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);

 

 

Input and Output

 

Input 

Parameter : 입력되는 정보의 형식

Argument : 그 형식에 맞게 실제로 입력한 값

 

Output

console화면, html, 파일 저장, 등

 

"nodejs console input parameters"' 검색

https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program

 

How do I pass command line arguments to a Node.js program?

I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this: $ node server.js folder h...

stackoverflow.com

// syntax 폴더 안에 conditional.js 파일
var args = process.argv;
console.log(args);

node syntax\conditional.js egoing

실행시켜 출력하면 ['..','...','egoing'] 이 출력됨 

 

☆ 1부터 counting하지 않고 0부터 counting함

0번 자리 : nodejs runtime의 위치

1번 자리 : 실행시킨 파일의 경로

2번 자리 : 사용자가 입력한 입력값

 

node syntax\conditional.js egoing k0214

실행시켜 출력하면 ['...', '...', 'egoing', 'k0214'] 이 출력됨

 

var args = process.argv;
console.log(args[2]);

if(args[2]=='1'){
    console.log('C1'); 
 }
else{
     console.log('C2');
 }

args[2] 는 배열의 2번 자리(사용자가 입력한 입력값) 을 의미

 

data 폴더를 생성하고 그 안에 CSS,HTML,JavaScript 라는 이름의 파일(txt)를 생성한다. 

파일 안에 각각의 내용을 저장한다. 

<기존의 main.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);

 

main.js 를 수정한다. 

fs.readFile 부분 작성 

`data/${queryData.id}` : file 이름 (data directory 밑에 있는 ${queryData.id} (쿼리스트링에 따라 파일명 생성) ) 

var template= `..` 부분을 fs.readFile{ } 안에 넣는다. 

template=` ` 안에 있는 <p>...</p> 부분을  <p>${description}</p> 로 변경한다. 

description 은 변수로 사용되는데, file에 있는 내용을 저장하고 있는 변수이다. 

    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);
    })
});

 

 

<전체코드>

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);

 

CRUD - 정보시스템의 핵심적 매커니즘

Create Read Update Delete

- 정보시스템에서 가장 먼저 알아야 할 것 : Create, Read 

Create, Read (50%) + 수정 삭제 (25%) + 엄청난 에너지 노력(25%)

 

" node.js file read "  - Node.js 로 파일을 읽고 싶을 때 검색 keyword

node.js 홈페이지에서 nod.js가 제공하는 모듈 중 "file system"

https://nodejs.org/dist/latest-v6.x/docs/api/fs.html

 

File System | Node.js v6.17.1 Documentation

File System# File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require('fs'). All the methods have asynchronous and synchronous forms. The asynchronous form always takes a completion callback as its last argumen

nodejs.org

ctrl+f 키를 눌러 "readFile" 을 검색하면 아래와 같은 화면이 나오는데, 이를 참고하여 코드를 짜고 공부하면 된다. 

"nodejs공부" 폴더 안에 "nodejs"폴더를 만들고 fileread.js 와 sample.txt를 생성

node fileread.js

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

sample.txt에는 아무 내용이나 넣었다. 

 

cmd창에서 

cd nodejs공부폴더 

node fileread.js를 실행시키니 다음과 같은 에러가 떴다.(loader.js:969  Error: Cannot find module)

sample.txt가 저장되어있는 nodejs폴더가 아닌 상위폴더에서 node 실행시켰기 때문에 sample.txt를 찾지 못해 생긴 에러이다. 

해당 파일이 있는 폴더로 가서 node실행시키면 결과가 나옴

 

 

<정적 웹 페이지>

저장된 그대로 웹 페이지에 보이는 것

<!doctype html>
<html>
<head>
  <title>WEB1 - HTML</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.html">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>HTML</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>

 

<동적 웹 페이지>

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);

동적인 웹페이지를 만들기 위해 template 변수 생성 -> template literals(``) 를 사용해서 html 코드를 넣음

query string에 따라 바뀌었으면 하는 부분에 ${queryData.id}로 대체

 

 

URL의 이해

http://opentutorials.org:3000/main?id=HTML&page=12

 

http : protocol 통신규칙. 사용자가 서버에 접속할 때 어떤 방식으로 서버에 접속할 것인지에 대한 부분. 웹브라우저가 웹서버와 서로 데이터를 주고받기 위해 만든 통신 규칙

opentutorials.org : domain(host) . 인터넷에 접속되어 있는 각각의 컴퓨터를 가리키는 주소

3000 : port 번호. 한개의 컴퓨터 안에 여러 대의 서버가 있을 수 있는데, 클라이언트가 접속했을 때 그 중에 3000번 서버에 연결한 것

main : path. 그 컴퓨터 안에 있는 어떤 디렉토리의 어떤 파일인지 가리킴

id=HTML&page=12 : query string. 이 값을 변경하면 웹서버에 데이터를 전달할 수 있음. 쿼리스트링의 시작은 ?임. 값의 이름과 값은 = 로 구분

 

 

URL을 통해서 입력된 값을 사용하는 방법

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'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    response.end(fs.readFileSync(__dirname + url));
 
});
app.listen(3000);

 

 

 

 

위 코드의 경우 : cmd창에서 파일을 실행시킨 후에 http://localhost:3000/을 주소창에 입력하면 된다. 

 

사용자가 주소를 입력 할 때, 쿼리스트링 부분에 다른 값이 들어올 때마다 그에 맞춰서 데이터를 보여 주어야할때

" node.js url parse query string " 검색 참고

즉, cmd 창에서 파일을 실행 시킨 후에 http://localhost/?id=HTML를 입력했을 시 그에 맞춰 데이터를 보여주어야 함

 

쿼리스트링 부분이 반영되는 코드 

var url = request.url;

console.log(url); 을 저 코드 밑에 넣어 확인 해 보면 /?id=HTML 이라는 값이 url 변수에 담겨진 것을 확인할 수 있음

( id값이 CSS라면 url 변수에는 /?id=CSS 가 대입되어있음)

 

아래의 코드를 추가 (의미 : "url이라는 모듈을 url이라는 변수를 이용하여 사용할 것" )

var url = require('url');

 

변수 url이 겹치므로 수정해 줄것 

var _var = request.url;

 

_url 변수에 들어온 쿼리스트링 값을 이용하기 위해 분석(parse)를 해주는 코드 작성 -> queryData 변수에 대입

여기서 HTML이라는 값을 얻으려면 queryData.id를 입력하면 됨

var queryData = url.parse(_url, true).query;
console.log(queryData);
console.log(queryData.id);

 

사용자가 접속한 url에 따라 해당하는 파일들을 읽어주는 코드 대신 화면에 HTML 혹은 CSS가 출력되도록 수정(쿼리스트링에 따라 다르게 동작)

//response.end(fs.readFileSync(__dirname + _url));
response.end(queryData.id);

 

전체 코드

 

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'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    response.end(queryData.id);
 
});
app.listen(3000);

+ Recent posts