Nodejs

 

 

인프런 :  https://www.inflearn.com/course/web2-node-js#

 

생활 코딩 :  https://opentutorials.org/module/3549

 

 

소스 :  https://github.com/braverokmc79/WEB2-Nodejs

 

 

App 

 

41.글생성 UI 만들기

 

 

const http = require('http');
const fs = require('fs');
const url = require("url");



function templateHTML(title, menuList, body) {
  return `
    <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>${menuList}</ol>
            <a href="/create">create</a>
            ${body}
    </body>
    </html>       
  `;
}

function templateList(filelist) {
  let menuList = "";
  filelist.forEach(item => {
    menuList += `<li><a href="/?id=${item}">${item}</a></li>`;
  })
  return menuList;
}

//공통 페이지 메뉴
function commonPage(queryData, response, head, body) {
  fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {
    let title = queryData.id;
    if (head === "main") {
      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
      }
      body = `<h2>${title}</h2>${description}`;
    } else if (head === "create") {
      title = "CREATE";
    }

    const template = templateHTML(title, templateList(fs.readdirSync('../data')), body);
    response.writeHead(200);
    response.end(template);
  });
}


const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;


  if (pathname === '/') {
    commonPage(queryData, response, "main", "");


  } else if (pathname === '/create') {
    commonPage(queryData, response, "create", `<form action="http://localhost:300/process_create" method="post">
        <p><input type="text" name="title" placeholder=""></p>
        <p><textarea name="description" style="width:200px; height:150px" ></textarea></p>
        <p><input type="submit"></p>
      </form>`);

  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

42.POST 방식으로 전송된 데이터 받기

 

const http = require('http');
const fs = require('fs');
const url = require("url");
const qs = require("querystring");


function templateHTML(title, menuList, body) {
  return `
    <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>${menuList}</ol>
            <a href="/create">create</a>
            ${body}
    </body>
    </html>       
  `;
}

function templateList(filelist) {
  let menuList = "";
  filelist.forEach(item => {
    menuList += `<li><a href="/?id=${item}">${item}</a></li>`;
  })
  return menuList;
}

//공통 페이지 메뉴
function commonPage(queryData, response, head, body) {
  fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {
    let title = queryData.id;
    if (head === "main") {
      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
      }
      body = `<h2>${title}</h2>${description}`;
    } else if (head === "create") {
      title = "CREATE";
    }

    const template = templateHTML(title, templateList(fs.readdirSync('../data')), body);
    response.writeHead(200);
    response.end(template);
  });
}


const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;


  if (pathname === '/') {
    commonPage(queryData, response, "main", "");


  } else if (pathname === '/create') {
    commonPage(queryData, response, "create", `<form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder=""></p>
        <p><textarea name="description" style="width:200px; height:150px" ></textarea></p>
        <p><input type="submit"></p>
      </form>`);
  } else if (pathname === '/create_process') {
    let body = "";
    request.on("data", function (data) {
      body = body + data;
    });

    request.on("end", function (data) {
      const post = qs.parse(body);
      let title = post.title;
      let description = post.description;

      console.log(post);
    });


    response.writeHead(200);
    response.end("success");
  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

 

 

43.파일생성과 리다이렉션

 

const http = require('http');
const fs = require('fs');
const url = require("url");
const qs = require("querystring");


function templateHTML(title, menuList, body) {
  return `
    <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>${menuList}</ol>
            <a href="/create">create</a>
            ${body}
    </body>
    </html>       
  `;
}

function templateList(filelist) {
  let menuList = "";
  filelist.forEach(item => {
    menuList += `<li><a href="/?id=${item}">${item}</a></li>`;
  })
  return menuList;
}

//공통 페이지 메뉴
function commonPage(queryData, response, head, body) {
  fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {
    let title = queryData.id;
    if (head === "main") {
      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
      }
      body = `<h2>${title}</h2>${description}`;
    } else if (head === "create") {
      title = "CREATE";
    }

    const template = templateHTML(title, templateList(fs.readdirSync('../data')), body);
    response.writeHead(200);
    response.end(template);
  });
}


const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;


  if (pathname === '/') {
    commonPage(queryData, response, "main", "");


  } else if (pathname === '/create') {
    commonPage(queryData, response, "create", `<form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder=""></p>
        <p><textarea name="description" style="width:200px; height:150px" ></textarea></p>
        <p><input type="submit"></p>
      </form>`);
  } else if (pathname === '/create_process') {
    let body = "";
    request.on("data", function (data) {
      body = body + data;
    });

    request.on("end", function (data) {
      const post = qs.parse(body);
      let title = post.title;
      let description = post.description;

      fs.writeFile(`../data/${title}`, description, 'utf8', function (err) {
        response.writeHead(302, { Location: `/?id=${title}` });
        response.end("success");
      })

    });



  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

 

 

44.수정 링크 생성

const http = require('http');
const fs = require('fs');
const url = require("url");
const qs = require("querystring");


function templateHTML(title, menuList, body) {
  return `
    <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>${menuList}</ol>          
            ${body}
    </body>
    </html>       
  `;
}

function templateList(filelist) {
  let menuList = "";
  filelist.forEach(item => {
    menuList += `<li><a href="/?id=${item}">${item}</a></li>`;
  })
  return menuList;
}

//공통 페이지 메뉴
function commonPage(queryData, response, head, body) {
  fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {
    let title = queryData.id;
    if (head === "main") {
      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
        body = `<a href="/create">create</a><h2>${title}</h2>${description}`;
      } else {
        body = `<a href="/create">create</a>&nbsp;&nbsp;&nbsp;<a href="/update?id=${title}">update</a><h2>${title}</h2>${description}`;
      }

    } else if (head === "create") {
      title = "CREATE";
    }

    const template = templateHTML(title, templateList(fs.readdirSync('../data')), body);
    response.writeHead(200);
    response.end(template);
  });
}


const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;


  if (pathname === '/') {
    commonPage(queryData, response, "main", "");


  } else if (pathname === '/create') {
    commonPage(queryData, response, "create", `<form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder=""></p>
        <p><textarea name="description" style="width:200px; height:150px" ></textarea></p>
        <p><input type="submit"></p>
      </form>`);
  } else if (pathname === '/create_process') {
    let body = "";
    request.on("data", function (data) {
      body = body + data;
    });

    request.on("end", function (data) {
      const post = qs.parse(body);
      let title = post.title;
      let description = post.description;

      fs.writeFile(`../data/${title}`, description, 'utf8', function (err) {
        response.writeHead(302, { Location: `/?id=${title}` });
        response.end("success");
      })

    });

  } else if (pathname === '/update') {
    response.writeHead(200);
    response.end("Not found");
  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

 

45.수정할 정보 전송

 

const http = require('http');
const fs = require('fs');
const url = require("url");
const qs = require("querystring");


function templateHTML(title, menuList, body) {
  return `
    <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ol>${menuList}</ol>          
            ${body}
    </body>
    </html>       
  `;
}

function templateList(filelist) {
  let menuList = "";
  filelist.forEach(item => {
    menuList += `<li><a href="/?id=${item}">${item}</a></li>`;
  })
  return menuList;
}

//공통 페이지 메뉴
function commonPage(queryData, response, head, body) {
  fs.readFile(`../data/${queryData.id}`, 'utf-8', function (err, description) {
    let title = queryData.id;
    if (head === "main") {
      if (queryData.id === undefined) {
        title = "Welcome";
        description = "Hello, Node.js";
        body = `<a href="/create">create</a><h2>${title}</h2>${description}`;
      } else {
        body = `<a href="/create">create</a>&nbsp;&nbsp;&nbsp;<a href="/update?id=${title}">update</a><h2>${title}</h2>${description}`;
      }

    } else if (head === "create") {
      title = "CREATE";

    } else if (head === "update") {
      body = `<form action="/update_process" method="post">
        <p><input type="hidden" name="id" value='${title}' ></p>
        <p><input type="text" name="title" value='${title}'></p>
        <p><textarea name="description" style="width:200px; height:150px" >${description}</textarea></p>
        <p><input type="submit" value="수정하기"></p>
      </form>`;

    }

    const template = templateHTML(title, templateList(fs.readdirSync('../data')), body);
    response.writeHead(200);
    response.end(template);
  });
}


const app = http.createServer(function (request, response) {
  const _url = request.url;
  const queryData = url.parse(_url, true).query;
  const pathname = url.parse(_url, true).pathname;


  if (pathname === '/') {
    commonPage(queryData, response, "main", "");


  } else if (pathname === '/create') {
    commonPage(queryData, response, "create", `<form action="/create_process" method="post">
        <p><input type="text" name="title" placeholder=""></p>
        <p><textarea name="description" style="width:200px; height:150px" ></textarea></p>
        <p><input type="submit"></p>
      </form>`);
  } else if (pathname === '/create_process') {
    let body = "";
    request.on("data", function (data) {
      body = body + data;
    });

    request.on("end", function (data) {
      const post = qs.parse(body);
      let title = post.title;
      let description = post.description;

      fs.writeFile(`../data/${title}`, description, 'utf8', function (err) {
        response.writeHead(302, { Location: `/?id=${title}` });
        response.end("success");
      })

    });

  } else if (pathname === '/update') {
    commonPage(queryData, response, "update", null);

  } else if (pathname === '/update_process') {
    response.writeHead(200);
    response.end("succes");

  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

 

 

 

46.파일명 변경, 내용 저장

 

const http = require('http');
const fs = require('fs');
const url = require("url");
const qs = require("querystring");


~

const app = http.createServer(function (request, response) {
  
~
  } else if (pathname === '/update') {
    commonPage(queryData, response, "update", null);

  } else if (pathname === '/update_process') {
    let body = "";
    request.on("data", function (data) {
      body = body + data;
    });

    request.on("end", function (data) {
      const post = qs.parse(body);
      const id = post.id;
      const title = post.title;
      const description = post.description;

      fs.rename(`../data/${id}`, `../data/${title}`, function (err) {
        fs.writeFile(`../data/${title}`, description, 'utf8', function (err) {
          response.writeHead(302, { Location: `/?id=${title}` });
          response.end("success");
        })
      })

    });

  } else {
    response.writeHead(400);
    response.end("Not found");
  }

});
app.listen(3000);

 

 

 

 

 

 

47.삭제버튼 구현

 

 

~

  body = `<a href="/create">create</a>&nbsp;&nbsp;&nbsp;
              <a href="/update?id=${title}">update</a>&nbsp;&nbsp;&nbsp;              
              <form method="post" >
                <input type="hidden" name="id" value='${title}' >
                <input type="submit" value="delete" style="">
              </form>
              <h2>${title}</h2>${description}`;


~

 

 

 

 

48.삭제버튼 구현

 

  } else if (pathname === '/delete_proecess') {
    let body = "";
    request.on("data", function (data) {
      body = body + data;
    });

    request.on("end", function (data) {
      const post = qs.parse(body);
      const id = post.id;
      fs.unlink(`../data/${id}`, function (error) {
        response.writeHead(302, { Location: `/` });
        response.end("success");
      });
    });


  }

 

 

 

 

 

 

JavaScript 객체

 

 

49.형식

 

 

 

 

50.반복

 

 

 

for in 반복문과 for of 반복문의 차이점

  • for in 반복문 : 객체의 모든 열거 가능한 속성에 대해 반복
  • for of 반복문 : [Symbol.iterator] 속성을 가지는 컬렉션 전용  배열 전용

 

Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};

var iterable = [3, 5, 7];
iterable.foo = "hello";

for (var key in iterable) {
  console.log(key); // 0, 1, 2, "foo", "arrCustom", "objCustom"
}

for (var value of iterable) {
  console.log(value); // 3, 5, 7
}

 

var members = ['egoing', 'k8805', 'hoya'];
console.log(members[1]); // k8805
var i = 0;
while (i < members.length) {
    console.log('array loop', members[i]);
    i = i + 1;
}

var roles = {
    'programmer': 'egoing',
    'designer': 'k8805',
    'manager': 'hoya'
}
console.log(roles.designer); //k8805
console.log(roles['designer']); //k8805

for (var key in roles) {
    console.log('object => ', key, 'value => ', roles[key]);
}

for (var value of members) {
    console.log('array => ', value);
}

 

 

 

 

51.객체 값으로서 함수

 

 

 

 

 

 

52.데이터와 처리 방법을 담는 그릇으로서 객체

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

성격이 모두 나와 같아지기를 바라지 말라. 매끈한 돌이나 거친 돌이나 다 제각기 쓸모가 있는 법이다. 남의 성격이 내 성격과 같아지기를 바라는 것은 어리석은 생각이다. -안창호

댓글 ( 4)

댓글 남기기

작성

Nodejs 목록    more