[생활코딩]Node.js : 1-12강

ChoHyerin·2024년 9월 22일
0

Node.js

목록 보기
1/3

1. 수업 소개 ~ 2. 수업의 목적

Node.js 폭발적 언어. 개쩖. → 이 댕 쩌는 언어를 배워보자!

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

  • 웹 서버로 사용 가능
response.end(fs.readFileSync(__dirname + url));
  • response.end() : 사용자에게 전송할 데이터 설정
  • fs.readFileSync(__dirname + url): 경로 설정된 파일 가져옴

6~8. JavaScript 문법

  • Number Data Type : 수식 넣으면 계산 결과 출력
    console.log(1+1); // 2
    console.log(1-1); // 0
    console.log(3*1); // 3
    console.log(4/2); // 2
  • String
    console.log('1'+'1'); // 11
    console.log('Hello World'.length); // 11 -> 띄어쓰기 포함
  • Variable : 변수 선언
    var a = 1;
    console.log(a); // 1
    a = 2;
    console.log(a); // 2
    : 변수 활용
    var greet = 'Hello World';
    console.log(greet); // Hello World
    
    var letter = greet + ', My name is Hyerin';
    // Hello World, My name is Hyerin
  • Template literals
    var greet = 'Hello World';
    var letter =' ${greet}, My name is Hyerin. ${1+1}';
    
    console.log(letter);
    /*
    Hello World, My name is Hyerin. 2
    
    ${} -> Template literal
    */
    
    var letter = greet + '\n\n, My name is Hyerin';
    
    console.log(letter);
    /*
    Hello World
    
    ,My name is Hyerin
    */

9. URL의 이해

  • protocol : 통신규칙
    → 사용자가 서버에 접속 시 어떤 방식으로 통신할 것인지 나타냄
    → http(Hyper Text Transfer Protocol) : 데이터를 주고 받기 위한 통신 규약

  • host(domain) : 호스트
    → 인터넷에 접속되어 있는 각각의 컴퓨터를 나타냄

  • port : 포트 번호
    → 한 대의 컴퓨터 안에 여러대의 서버가 있을 수 있기에 어떤 서버와 통신할지 정함

  • path : 파일
    어떤 파일인지 가리킴

  • query string : 쿼리 스트링
    → 이 값을 변경하면 웹 서버에 어떤 데이터를 전달 가능
    • ?로 시작하기로 약속
    • &으로 값과 값을 구분
    • =으로 값의 이름과 값 구분

10. URL을 통해 입력된 값 사용하기

→ 색칠된 부분 = 쿼리 스트링

var http = require('http');
var fs = require('fs');
var url = require('url'); // url이라는 모듈을 사용할 것이다.

var app = http.createServer(function(request,response){
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  //url 모듈을 통해 받은 객체의 parse 메소드의 parameter로 _url을 넣어 실행
  console.log(queryData); 
  // { id = HTML } 
  console.log(queryData.id);
  // id값 나옴, query string에 따라서 다른 정보 출력 가능
  
  console.log(_url);
  if(_url == '/'){
    _url = '/index.html';
  }
  if(_url == '/favicon.ico'){
    return response.writeHead(404);
  }
  response.writeHead(200);
  response.end(queryData.id);
});
app.listen(3000);

11. 동적인 웹페이지 만들기

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

var app = http.createServer(function(request,response){
  var _url = request.url;
  var queryData = url.parse(_url, true).query;
  console.log(queryData.id);
  if(_url == '/'){
    _url = '/index.html';
  }
  if(_url == '/favicon.ico'){
    return response.writeHead(404);
  }
  response.writeHead(200);
  var template = `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - HTML</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="index.html">WEB</a></h1>
    <ol>
      <li><a href="1.html">HTML</a></li>
      <li><a href="2.html">CSS</a></li>
      <li><a href="3.html">JavaScript</a></li>
    </ol>
    <h2>HTML</h2>
    <p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
    <img src="coding.jpg" width="100%">
    </p><p style="margin-top:45px;">HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets.
    </p>
  </body>
  </html>
  
  `;
  response.end(queryData.id);
});
app.listen(3000);

위 정적 페이지를 아래 동적 페이지로 바꾼다.

(제목 부분을 동적으로 바꿈)

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(title);
  if(_url == '/'){
    title = 'Welcome';
  }
  if(_url == '/favicon.ico'){
    return response.writeHead(404);
  }
  response.writeHead(200);
  var template = `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${title}</title> <!-- 여기 -->
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB</a></h1>
    <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);

12. 파일 읽기 기능

  • CRUD : Create, Read, Update, Delete
  • readFile()
    var fs = require('fs');
    fs.readFile('sample.txt', 'uft8',fundtion(err, data){
    	console.log(data);
    	//fs.readFile( 파일명(파일 경로), 옵션, 콜백함수 )
    });
    → fs 모듈 이용하면 사용 가능.

끄읕.

0개의 댓글