컴퓨터/nodejs

Node.js 생활코딩

풍경소리^^ 2023. 3. 29. 12:50

https://www.youtube.com/playlist?list=PLuHgQVnccGMA9QQX5wqj6ThK7t2tsGxjm 

 

WEB2 - Node.js

 

www.youtube.com

https://opentutorials.org/module/3549

 

Node.js

수업소개 이 수업은 JavaScript를 이용해서 Node.js를 제어해 동적으로 HTML 코드를 생성하는 웹애플리케이션을 만드는 방법에 대한 수업입니다.  수업대상 예를들어 1억개의 페이지로 이루어진 웹사

opentutorials.org

Node.js - 5.Node.js로 웹서버 만들기

main.js--------------------

var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request,response){
	var url = request.url;
    if(url == '/'){
    	url = '/index.html';
    }
    if(url == '/favicon.ico'){
    	return response.writeHead(404);
    }
    response.writeHead(200);
    console.log(__dirname + url);
    response.end(fs.readFileSync(__dirname + url));
});
app.listen(3000);

 

Node.js - 10.URL을 통해서 입력된 값 사용하기

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;
    console.log(_url);
    console.log(queryData);
    console.log(queryData.id);
    if(_url == '/'){
      _url = '/index.html';
    }
    if(_url == '/favicon.ico'){
        response.writeHead(404);
        response.end();
        return;
    }
    response.writeHead(200);
    console.log(__dirname + _url);
    response.end(fs.readFileSync(__dirname + _url));
    // response.end('egoing : ' + _url);
    
});
app.listen(3000);

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

Node.js-11.App 제작-동적인 웹페이지 만들기

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;
  console.log(queryData.id);
  if(_url == '/'){
    _url = '/index.html';
  }
  if(_url == '/favicon.ico'){
      response.writeHead(404);
  }
  response.writeHead(200);
  var template = `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${queryData.id}</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>${queryData.id}</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--------------------

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.writeHead(200);
  var template = `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${queryData.id}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="index.html">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>${queryData.id}</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--------------------

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;
  console.log(queryData.id);
  if(_url == '/'){
    _url = '/index.html';
  }
  if(_url == '/favicon.ico'){
      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="index.html">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--------------------

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;
  console.log(queryData.id);
  if(_url == '/'){
    title = 'Welcome';
  }
  if(_url == '/favicon.ico'){
      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>
    <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);

Node.js-12.Node.js의 파일 읽기 기능

nodejs-sample.txt--------------------

nodejs-fileread.js--------------------

const fs = require('fs');

fs.readFile('sample.txt', 'utf8', function(error,data){
  console.log(data);
});

cd nodejs

node fileread.js

cd ..

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

data-HTML

data-CSS

data-JavaScript

 

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;
  console.log(queryData.id);
  if(_url == '/'){
    title = 'Welcome';
  }
  if(_url == '/favicon.ico'){
      response.writeHead(404);
  }
  response.writeHead(200);
  fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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);

node main.js

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

tyntax/conditional.js--------------------

var args = process.argv;
console.log(args);

$ node syntax/conditional.js egoing k8805
[
  'C:\\Program Files\\nodejs\\node.exe',
  'B:\\nodejs\\syntax\\conditional.js',
  'egoing',
  'k8805'
]

tyntax/conditional.js--------------------

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

$ node syntax/conditional.js egoing k8805
[
  'C:\\Program Files\\nodejs\\node.exe',
  'B:\\nodejs\\syntax\\conditional.js',
  'egoing',
  'k8805'
]
egoing

tyntax/conditional.js--------------------

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

$ node syntax/conditional.js 1
[
  'C:\\Program Files\\nodejs\\node.exe',
  'B:\\nodejs\\syntax\\conditional.js',
  '1'
]
1
----------
C1

Node.js-19.1.App 제작-Not found 구현

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;
  
  fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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.writeHead(200);
    response.end(template);
  })
});
app.listen(3000);

main.js--------------------console로 찍어보자

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;

  console.log(url.parse(_url, true));
  
  fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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.writeHead(200);
    response.end(template);
  })
});
app.listen(3000);

$ node main.js

서버가동되면 브라우저에

http://localhost:3000/


Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: [Object: null prototype] {},
  pathname: '/',
  path: '/',
  href: '/'
}
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: [Object: null prototype] {},
  pathname: '/favicon.ico',
  path: '/favicon.ico',
  href: '/favicon.ico'
}

 

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 pathname = url.parse(_url, true).pathname;
  var title = queryData.id;

  if(pathname === '/'){
    fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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.writeHead(200);
      response.end(template);
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

node main.js

웹브라우저에서

localhost:3000/ttt

 

Not found

 

Node.js-19.2.App 제작-홈페이지 구현

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 pathname = url.parse(_url, true).pathname;
  
  if(pathname === '/'){
    if(queryData.id === undefined){
      // fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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>
        <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.writeHead(200);
        response.end(template);
      // });
    } else {
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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>
        <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.writeHead(200);
        response.end(template);
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

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

nodejs-readdir.js--------------------

const testFolder = 'data/';
const fs = require('fs');

fs.readdir(testFolder, function(error, filelist){
  console.log(filelist);
  console.log('----------');
  filelist.forEach(file => {
    console.log(file);
  })
})

$ node nodejs/readdir.js
[ 'CSS', 'HTML', 'JavaScript' ]
----------
CSS
HTML
JavaScript

Node.js-24.App 제작-글목록 출력하기

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 pathname = url.parse(_url, true).pathname;
  
  if(pathname === '/'){
    if(queryData.id === undefined){
      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>
      <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.writeHead(200);
      response.end(template);
    } else {
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,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>
        <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.writeHead(200);
        response.end(template);
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

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 pathname = url.parse(_url, true).pathname;
  
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        console.log(filelist);
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        /*
        var list = `
          <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>
        `;
        */
        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.readFile(`data/${queryData.id}`, 'utf8', function(error,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>
        <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.writeHead(200);
        response.end(template);
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

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 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.readFile(`data/${queryData.id}`, 'utf8', function(error,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>
        <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.writeHead(200);
        response.end(template);
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

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 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(error,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>
          <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.writeHead(200);
          response.end(template);
        });
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

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 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(error,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);

Node.js26.App 제작-함수를 이용해서 정리 정돈하기

main.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>  
`;
}

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 = templateHTML(title, list, `<h2>${title}</h2><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });

      
    } else {
      fs.readdir('./data', function(error, 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>';
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var template = templateHTML(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-28.3.JavaScript-callback

syntax-callback.js--------------------

/*
function a() {
  console.log('A');
}
a();
*/
var a = function () {
  console.log('A');
}
a();

syntax-callback.js--------------------

var a = function(){
  console.log('A');
}

function slowfunc(callback){
  callback();
}

slowfunc(a);

Node.js-29.Node.js의 패키지 매니저와 PM2

Package Manager

npm install pm2 -g

pm2 start main.js --watch

pm2 monit

pm2 log

Node.js-30.HTML-form

form.html--------------------

<form action="http://localhost:3000/process_create" method="post">
  <p><input type="text" name="title"></p>
  <p><textarea name="description" id="" cols="30" rows="10"></textarea></p>
  <p><input type="submit"></p>
</form>

Node.js-31.App 제작-글생성 UI 만들기

main.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}
  <a href="/create">create</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/process_create" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-32.App 제작-POST 방식으로 전송된 데이터 받기

main.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}
  <a href="/create">create</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

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}
  <a href="/create">create</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
    });
    response.writeHead(200);
    response.end("success");
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

localhost:3000

create

ddd

ddd is ...

 

[Object: null prototype] { title: 'ddd', description: 'ddd is ...' }

 

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

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}
  <a href="/create">create</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
    });
    response.writeHead(200);
    response.end("success");
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-33.App 제작-파일생성과 리다이렉션

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

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}
  <a href="/create">create</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(200);
        response.end("success");
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

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}
  <a href="/create">create</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-34.App 제작-글수정-수정링크생성

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

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}
  <a href="/create">create</a> <a href="/update">update</a>
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list, `<h2>${title}</h2><p>${description}</p>`);
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`);
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `);
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
           `<a href="/create">create</a>`
           );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
           `<a href="/create">create</a>`
           );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-35.App 제작-글수정-수정할 정보 전송

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
           `<a href="/create">create</a>`
           );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
           `<h2>${title}</h2><p>${description}</p>`,
           `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
           `<a href="/create">create</a>`
           );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="http://localhost:3000/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="http://localhost:3000/create_process" method="post">
            <p><input type="text" name="title" placeholder="title"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
           `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
           `<a href="/create">create</a>`
           );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
           `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
           `<a href="/create">create</a>`
           );
        response.writeHead(200);
        response.end(template);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHtml(title, list,
             `<h2>${title}</h2><p>${description}</p>`,
             `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body);
      console.log(post);
      var title = post.title;
      console.log(post.title);
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
           `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-36.App 제작-글수정-파일명 변경, 내용저장

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      console.log(post); // post 에서 받아온 title
      // fs.writeFile(`data/${title}`, description, 'utf8',function(err){
      //   response.writeHead(302, {Location: `/?id=${title}`});
      //   response.end();
      // })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js-------------------file rename using nodejs

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        
      })
      // fs.writeFile(`data/${title}`, description, 'utf8',function(err){
      //   response.writeHead(302, {Location: `/?id=${title}`});
      //   response.end();
      // })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js-------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-37.App 제작-글삭제-삭제버튼 구현

main.js-------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <a href="/delete?id=${title}">delete</a>` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js-------------------delete button

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form>
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-38.App 제작-글삭제 기능 완성

main.js--------------------nodejs delete file

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
  <h1><a href="/">WEB</a></h1>
  ${list}
  ${control}
  ${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;
  console.log(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><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        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><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = templateList(filelist);
      var template = templateHtml(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(template);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = templateList(filelist);
        var template = templateHtml(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(template);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      fs.unlink(`data/${id}`, function(error){
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-39.JavaScript 객체의 형식

https://opentutorials.org/module/3549/21143

 

JavaScript - 객체의 형식 - Node.js

수업소개 서로 연관된 데이터를 정리 정돈하는 도구인 객체의 형식을 살펴보겠습니다.  강의 소스코드 main.js (변경사항) var members = ['egoing', 'k8805', 'hoya']; console.log(members[1]); // k8805 var roles = { 'pro

opentutorials.org

Node.js-40.JavaScript-객체-반복

https://opentutorials.org/module/3549/21144

 

JavaScript - 객체의 반복 - Node.js

수업소개 객체의 데이터를 하나씩 꺼내서 반복적인 처리를 하는 방법을 살펴보겠습니다.  강의 소스코드 syntax/object.js (변경사항) var members = ['egoing', 'k8805', 'hoya']; console.log(members[1]); // k8805 var i

opentutorials.org

Node.js-41.JavaScript-객체-값으로서 함수

https://opentutorials.org/module/3549/21145

 

JavaScript - 객체 - 값으로서 함수 - Node.js

수업소개 자바스크립트에서 함수는 구문(statement)이면서 동시에 값(value)이기도 합니다. 이런 특성을 이용하면 서로 연관된 데이터(변수)와 처리(함수)를 그룹핑해서 정리 정돈할 수 있습니다. 이

opentutorials.org

Node.js-42.JavaScript-객체-데이터와 처리 방법을 담는 그릇으로서 객체

https://opentutorials.org/module/3549/21146

 

JavaScript - 객체 - 데이터와 값을 담는 그릇으로서 객체 - Node.js

수업소개 객체를 이용해서 프로그래밍을 하는 방법에 대해서 살펴보겠습니다.  강의 소스코드 syntax/object3.js var q = { v1:'v1', v2:'v2', f1:function (){ console.log(this.v1); }, f2:function(){ console.log(this.v2); } } q

opentutorials.org

this 설명

Node.js43.App제작-템플릿 기능 정리정돈하기

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

var template = {
  Html:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>  
  `;
  }, List: function(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;
  }
}

function templateHtml(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
  <title>WEB1 - ${title}</title>
  <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    ${control}
    ${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;
  console.log(pathname);
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `<h2>${title}</h2><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        response.writeHead(200);
        response.end(html);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
          var title = queryData.id;
          var list = template.List(filelist);
          var html = template.Html(title, list,
            `<h2>${title}</h2><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = template.List(filelist);
      var html = template.Html(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(html);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      fs.unlink(`data/${id}`, function(error){
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

var template = {
  Html:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>  
  `;
  }, List: function(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;
  console.log(pathname);
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `<h2>${title}</h2><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        response.writeHead(200);
        response.end(html);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
          var title = queryData.id;
          var list = template.List(filelist);
          var html = template.Html(title, list,
            `<h2>${title}</h2><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = template.List(filelist);
      var html = template.Html(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(html);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      fs.unlink(`data/${id}`, function(error){
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-44.Node.js 모듈의형식

https://opentutorials.org/module/3549/21148

 

Node.js - 모듈의 형식 - Node.js

수업소개 많아진 코드를 정리 정돈하는 가장 큰 도구인 모듈의 형식을 살펴보겠습니다.  강의 소스코드 nodejs/mpart.js var M = { v:'v', f:function(){ console.log(this.v); } } module.exports = M; muse.js // var M = { // v

opentutorials.org

Node.js-45.App 제작 - 모듈의 활용

lib-template.js--------------------

module.exports = {
  Html:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>  
  `;
  }, List: function(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;
  }
}

// module.exports = template;

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
var template = require('./lib/template.js');

var template = {
  Html:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>  
  `;
  }, List: function(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;
  console.log(pathname);
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `<h2>${title}</h2><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        response.writeHead(200);
        response.end(html);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
          var title = queryData.id;
          var list = template.List(filelist);
          var html = template.Html(title, list,
            `<h2>${title}</h2><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = template.List(filelist);
      var html = template.Html(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(html);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(error,description){
        var title = queryData.id;
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      fs.unlink(`data/${id}`, function(error){
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-46.App 제작-입력정보에 대한 보안

password.js--------------------

module.exports = {
  id:'egoing',
  password:'111111'
}

localhost:3000/?id=../password.js

 

var path = require('path');

path.parse('../password.js');

 

{

root: '',

dir: '..',

base: 'password.js',

ext: '.js',

name: 'password'

}

 

path.parse('../password.js').base;

 

'password.js'

경로 세탁

 

main.js--------------------nodejs path parse

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
var template = require('./lib/template.js');
var path = require('path'); // 보안

var template = {
  Html:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>  
  `;
  }, List: function(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;
  console.log(pathname);
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `<h2>${title}</h2><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        response.writeHead(200);
        response.end(html);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        var filteredId = path.parse(queryData.id).base; // 보안
        fs.readFile(`data/${filteredId}`, 'utf8', function(err,description){ // 보안
          var title = queryData.id;
          var list = template.List(filelist);
          var html = template.Html(title, list,
            `<h2>${title}</h2><p>${description}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${title}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${title}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = template.List(filelist);
      var html = template.Html(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(html);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      var filteredId = path.parse(queryData.id).base;  // 보안
      fs.readFile(`data/${filteredId}`, 'utf8', function(error,description){ // 보안
        var title = queryData.id;
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      var filteredId = path.parse(id).base; // 보안
      fs.unlink(`data/${filteredId}`, function(error){ // 보안
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-47.1.App제작-출력정보에 대한 보안

공격자가 아래 글을 게시하면

xss

<script>

  alert('merong');

  location.href = 'https://opentutorials.org/';

</script>

 

script 태그로 입력이 들어오면 그냥 지운다

꺽쇄를 그대로 출력 html entities

https://www.w3schools.com/html/html_entities.asp

 

HTML Entities

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

Node.js-47.2.App제작-출력정보에 대한 보안

소독, 살균 npm sanitize html

====================

npm init

package name: 그냥 계속 enter

그러면 package.json 파일이 생긴다

 

npm install -S sanitize-html

====================

Node.js-47.3.App제작-출력정보에 대한 보안

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
var template = require('./lib/template.js');
var path = require('path'); // 보안
var sanitizeHtml = require('sanitize-html');

var template = {
  Html:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>  
  `;
  }, List: function(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;
  console.log(pathname);
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `<h2>${title}</h2><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        response.writeHead(200);
        response.end(html);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        var filteredId = path.parse(queryData.id).base; // 보안
        fs.readFile(`data/${filteredId}`, 'utf8', function(err,description){ // 보안
          var title = queryData.id;
          var sanitizedTitle = sanitizeHtml(title);
          var sanitizedDescription = sanitizeHtml(description);
          var list = template.List(filelist);
          var html = template.Html(title, list,
            `<h2>${sanitizedTitle}</h2><p>${sanitizedDescription}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${sanitizedTitle}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${sanitizedTitle}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = template.List(filelist);
      var html = template.Html(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(html);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      var filteredId = path.parse(queryData.id).base;  // 보안
      fs.readFile(`data/${filteredId}`, 'utf8', function(error,description){ // 보안
        var title = queryData.id;
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      var filteredId = path.parse(id).base; // 보안
      fs.unlink(`data/${filteredId}`, function(error){ // 보안
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

main.js--------------------

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
var template = require('./lib/template.js');
var path = require('path'); // 보안
var sanitizeHtml = require('sanitize-html');

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;
  console.log(pathname);
  if(pathname === '/'){
    if(queryData.id === undefined){
      fs.readdir('./data', function(error, filelist){
        var title = 'Welcome';
        var description = 'Hello, Node.js'
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `<h2>${title}</h2><p>${description}</p>`,
          `<a href="/create">create</a>`
          );
        response.writeHead(200);
        response.end(html);
      });
    } else {
      fs.readdir('./data', function(error, filelist){
        var filteredId = path.parse(queryData.id).base; // 보안
        fs.readFile(`data/${filteredId}`, 'utf8', function(err,description){ // 보안
          var title = queryData.id;
          var sanitizedTitle = sanitizeHtml(title);
          var sanitizedDescription = sanitizeHtml(description, {
            allowedTags: ['h1']
          });
          var list = template.List(filelist);
          var html = template.Html(title, list,
            `<h2>${sanitizedTitle}</h2><p>${sanitizedDescription}</p>`,
            `
              <a href="/create">create</a>
              <a href="/update?id=${sanitizedTitle}">update</a>
              <form action="delete_process" method="post">
                <input type="hidden" name="id" value="${sanitizedTitle}">
                <input type="submit" value="delete">
              </form>
            ` // 이렇게 하면 안된다
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    }
  } else if(pathname === '/create') {
    fs.readdir('./data', function(error, filelist){
      var title = 'WEB - create';
      var list = template.List(filelist);
      var html = template.Html(title, list, `
      <form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder="title"></p>
        <p><textarea name="description" id="" cols="30" rows="10" placeholder="description"></textarea></p>
        <p><input type="submit"></p>
      </form>
      `, '');
      response.writeHead(200);
      response.end(html);
    });
  } else if(pathname === '/create_process') {
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      fs.writeFile(`data/${title}`, description, 'utf8',function(err){
        response.writeHead(302, {Location: `/?id=${title}`});
        response.end();
      })
    });
  } else if(pathname === "/update"){
    fs.readdir('./data', function(error, filelist){
      var filteredId = path.parse(queryData.id).base;  // 보안
      fs.readFile(`data/${filteredId}`, 'utf8', function(error,description){ // 보안
        var title = queryData.id;
        var list = template.List(filelist);
        var html = template.Html(title, list,
          `
          <form action="/update_process" method="post">
            <input type="hidden" name="id" value="${title}">
            <p><input type="text" name="title" placeholder="title" value="${title}"></p>
            <p><textarea name="description" id="" cols="30" rows="10" placeholder="description">${description}</textarea></p>
            <p><input type="submit"></p>
          </form>
          `,
          `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
        );
        response.writeHead(200);
        response.end(html);
      });
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });
  } else if(pathname === "/update_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      var title = post.title;
      // console.log(post.title); // post 에서 받아온 title
      var description = post.description;
      // console.log(post.titl); // post 에서 받아온 title
      fs.rename(`data/${id}`, `data/${title}`, function(error){
        fs.writeFile(`data/${title}`, description, 'utf8',function(err){
          response.writeHead(302, {Location: `/?id=${title}`});
          response.end();
        })
      })
    });} else if(pathname === "/delete_process"){
    var body = '';
    request.on('data', function(data){ // post 방식 데이터 가져올 때
      body = body + data;
    });
    request.on('end', function(){
      var post = qs.parse(body); // 받은 정보를 객체화
      // console.log(post); // post 에서 받아온 데이터
      var id = post.id;
      // console.log(post.title); // post 에서 받아온 title
      var filteredId = path.parse(id).base; // 보안
      fs.unlink(`data/${filteredId}`, function(error){ // 보안
        response.writeHead(302, {Location: `/`});
        response.end();
      })
    });
  } else {
    response.writeHead(404);
    response.end('Not found');
  }
});
app.listen(3000);

Node.js-48. API와 CreateServer

Application Programming Interface

Node.js-49.부록 - pm2 보충학습

 

https://opentutorials.org/module/3549/22110

 

보충수업 - PM2 사용법 - Node.js

수업소개 앞으로 학습하다보면 pm2의 동작 방법을 몰라서 고생할 수 있는 지점들이 있습니다. 이를 완화하기 위해서 추가로 제작된 수업입니다.  pm2로 실행한 모든 프로세스를 중지 & 삭제 합니

opentutorials.org

pm2 start main.js --watch --ignore-watch="data/* sessions/*" --no-daemon