201126 TIL NodeJs Basics

ToastEggsToast·2020년 11월 27일
0

NodeJs

목록 보기
2/4
post-thumbnail

UnderStanding the Basics


How The Web Works (refresher)

User/Client(Browser)에서 url을 통해 입장 -> Domain Lookup (맞는 서버로 감) -> Request -> Server (서버사이드 코드, 데이터베이스) -> 응답으로 HTML Page 등이 보내짐
Node.js 서버사이드 언어

HTTP, HTTPS

Hyper Text Transfer Protocol

  • A Protocol for Trnasferring Data which is understood by Browser and Server

Hyper Text Transfer Protocol Secure

  • HTTP + DataEncryption (during Transmission)

Creating a Node.js Server

Core Modules

http Launch a server, send requests
https Launch a SSL server
fs
path
os

Node.js Program Lifecycle

node app.js > start script > parse code, register variables & functions > calls eventloop (keeps running as long as there are eventlisteners registered) : The Node Application > proccess.exit

Using Node Core Modules

const http = require("http");

// function rqListener(req, res) {

// }
//  server에 닿는 request 처리에 대한 함수

const server = http.createServer((req, res) => {
  console.log("url: ", req.url);
  console.log("method: ", req.method);
  console.log("headers: ", req.headers);
  // process.exit();
  // server를 종료함!

  // request: Obejct

  res.setHeader("Content-Type", "text/html");
  res.write("<html>");
  res.write("<head><title>Node.js</title></head>");
  res.write("<body><h1>Hello from my Node js Server</h1></body>");
  res.write("</html>");
  res.end();
  // end 하고 나면 write를 할 수 없음!!
});
//  server 를 리턴해준다.

server.listen(3000);
// incoming req listen

Streams & Buffers

앞에꺼 다 끝내고.. 뒤에 할려고 뒤에 있는 요청들을 대기시키는것.

Working with Requests and Responses(Basics)

Asynchronous Code & The Event Loop

wrtieFile writeFileSync 차이점. 35? 36번 강의

Single Thread, Event Loop & Blocking Code

Worker Pool - Do the Heavy Lifting -> Trigger Callback

The Event Loop

Timers : Execute setTimeout, setInterval Callbacks
Pending Callbacks: Execute I/O-related callbacks that were deffered

  • I/O : Input.Output Disk and Network Operations(~Blocking Operations)
    Poll : Retrieve new I/O events, execute their callbacks
    Check : Execute setImmediate() callbacks
    Close Callbacks: Execute all 'close' event callbacks

최종으로 맨 마지막에 process.exit 실행..?

Using the Node Modules System

// before
const http = require("http");
const fs = require("fs");

// function rqListener(req, res) {

// }
//  server에 닿는 request 처리에 대한 함수

const server = http.createServer((req, res) => {
  // console.log("url: ", req.url);
  // console.log("method: ", req.method);
  // console.log("headers: ", req.headers);

  // request: Obejct

  const url = req.url;
  const method = req.method;

  if (url === "/") {
    res.write("<html>");
    res.write("<head><title>Enter Message</title></head>");
    res.write(
      "<body><form action='/message' method='POST'><input type='text' name='message'><button type='submit'>Send</button></form></body>"
    );
    res.write("</html>");
    return res.end();
  }

  if (url === "/message" && method === "POST") {
    const body = [];
    req.on("data", (chunk) => {
      console.log("chunk", chunk);
      body.push(chunk);
    });
    // event를 들을 수 있게 해줌.

    return req.on("end", () => {
      const parsedBody = Buffer.concat(body).toString();
      const message = parsedBody.split("=")[1];
      // console.log("parsedBPody", parsedBody);
      //  ~~~ = parsedBody인데 ~~~는 input의 name과 맞춰져있다.
      fs.writeFile("message.txt", message, (err) => {
        res.statusCode = 302;
        res.setHeader("Location", "/");
        return res.end();
      });
      // res.writeHead(302, {})
    });
  }

  //  req.on("end") 보다 먼저 읽히고 나서 => 그 뒤에 req.on("end")과 관련된 함수가 실행됨
  res.setHeader("Content-Type", "text/html");
  res.write("<html>");
  res.write("<head><title>Node.js</title></head>");
  res.write("<body><h1>Hello from my Node js Server</h1></body>");
  res.write("</html>");
  res.end();

  // end 하고 나면 write를 할 수 없음!!

  // process.exit();
  // server를 종료함!
});
//  server 를 리턴해준다.

server.listen(3000);
// incoming req listen

// This is the Raw Logic!!!

Module Summary

How to Web works

client request Server response client

Program LifeCycle & Event Loop

Node.js runs non-blocking JS code and uses an event=driven code("Event Loop") for running your login
A Node program exits as soon as there is no more work to do
Note: The createServer() event never finishes by default

Asynchronous Code

JS code is non-blocking
Use callbacks and events => Order Changes

Requests & Responses

Parse request data in chunks (Streams & Buffers)
Avoid double responses

Node.js & Core Modules

Node.js Ships with multiple core modules : http fs path
Core modules can be imported into any file to be used there
Import via require('module')

Node Module System

Import via require('./path-to-file') for custom files or require('module') for core and third-party modules
Export via module.exports or just exports for multiple exports)

profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글