ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Node.js - study part 1
    CodeingTestPrac 2022. 5. 13. 16:56

     

     

     

    >>>  사용자의 반응을 반영하는 웹패이지,,,,      html 파일을 직접적으로 건드는것은 위험함, 

    js  -> web 을 만든다

    node.js -> 컴퓨터를 제어 하여 서버를 만든고 web application 을 만든다. 

     

    사용자 입장 -> 웹사이트 CRUD 

    nod.js -> 파일 생성 코드를 생성

     

    [web application] >>>>>>>>>>>>>>>>>>>>.   [node.js application]

    [webbrowser].   ->>>>>>>>>>>>>>>>>>>.      [java script]

                                                                                      [node.js runtime]

     

     

    node.js org 방문  : 다운

    npm -> node js package manage program

    in mac enter open terminal or iterm program

    $ node -v

    $node

    vs code write file   and run in terminal

    [pwd]  > $node test.js

     

    --------------------------------------------------------------------------------------------

     

     

    code of file [main.js]

     

    var http = require('http');

    var fs = require('fs');

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

    });
    app.listen(3000);
     
     
     
     

    GitHub - web-n/web1_html_internet

    Contribute to web-n/web1_html_internet development by creating an account on GitHub.

    github.com

     
     
    -----------------------------
    만약 코드에서 response.end(fs.readFileSyn()); 가 없다면 
    웹상에서 페이지가 없다. -> flie sync
    node js 를 이용하여 사용자에게 데이터를 전송한다.
     
     
     
     
    ------- 기본 문법---   파이썬이랑 상당히 유사   literal temple 가능
    1. 변수 선언 및 연산자 이용
     
    변수 - 
    var:  function- scoped,,,,,, 변수 재선언 가능
     
    cinst , let:  block-scoped,,,,,,, 변수 재선언 불가
     
     
     
    // let
    let a = 'test'
    let a = 'test2' // Uncaught SyntaxError: Identifier 'a' has already been declared
    a = 'test3'     // 가능
    
    // const
    const b = 'test'
    const b = 'test2' // Uncaught SyntaxError: Identifier 'a' has already been declared
    b = 'test3'    // Uncaught TypeError:Assignment to constant variable.
     
     
     
    타입 변화 : 
     
    문자열 길이  length() 이용   ex ).  'apple'.length  ,   줄바꿈 :        '  \n '
                                                           console.log('ad'+a+'ac').  이거 가능
    templates literal useage :
     

    [JavaScript] ES6 템플릿 리터럴에 대해 알아보자!!

    [JavaScript] ES6 템플릿 리터럴에 대해 알아보자!! 안녕하세요. 이번 포스팅은 ES6의 템플릿 리터럴과 활용법에 대해 알아봅니다. Template literals 템플릿 리터럴 은 내장된 표현식을 허용하는 문자열

    eblee-repo.tistory.com

     
     
    In mac os  > option+ (one key or ~)
     
    ------
     
    2출력 
    3. 반복문
    4. 조건문 제어문
    5.배열 및 기타 자료구조
     
     
     
    ------------------------------------------------------------------------------------
     
     
    protocol :
    http:
     
     
     
     
     
    port :  하나의 컴퓨터의 여러 서버가 있으니 포트넘버를 부여하여 구분을 한다.
    웹은 기본 포트 80 을 사용하니 http 를 사용하여 접속을 하면 포트 80을 자동으로 
    쿼리string 는 ? 로 시작.
     
     

     

    주소:

    http://localhost:3000/?name=3.html

    var http = require('http');
    var fs = require('fs');
    var url = require('url');   // require module?
    
    var app = http.createServer(
        function (request, response) {
            var _url = request.url;
            console.log("_url: ");
            console.log(_url);
            console.log("------------");
            //url parsing
            var querydata = url.parse(_url,true).query;
            console.log("querydataat below");
            console.log(querydata);
            console.log("querydata.name at below");
            console.log(querydata.name);
    
            if (_url == '/') 
            {
            _url = '/index.html';
            }
    
            if (_url == '/favicon.ico') 
            {
            response.writeHead(404);
            response.end();
            return;
            }
            response.writeHead(200);
            response.end(querydata.name)
            // response.end(fs.readFileSync(__dirname + url));
        }
    );
    
    app.listen(3000); /// app.listen([portnum])

     

    node.js 

    -> require().  외부 모듈을 불러 온다, import  파이썬

     

     

    
    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)
        var title = queryData.id;
        if (_url == '/') {
            title = 'Welcome';
        }
        if (_url == '/favicon.ico') {
            return response.writeHead(404);
        }
        response.writeHead(200);
        fs.readFile(`/Users/chosunghyun/Desktop/nodejs/data/${queryData.id}`, 'utf-8', function (err, description) 
        {
            console.log(description)
            var template = `
          <!doctype html>
          <html>
          <head>
            <title>WEB1 - ${title}</title>
            <meta charset="utf-8">
          </head>
          <body>
            <h1><a href="/">WEB</a></h1>
            <ul>
              <li><a href="/?id=HTML">HTML</a></li>
              <li><a href="/?id=CSS">CSS</a></li>
              <li><a href="/?id=JavaScript">JavaScript</a></li>
            </ul>
            <h2>${title}</h2>
            <p>${description}</p>
          </body>
          </html>
          `;
            response.end(template);
        })
    
    
    });
    app.listen(3000);

     

     

     

    CRUD -> create read update delete

     

    File - CRUD 하는법 ? -> require('fs');

    read:

    fs.readfile(path/filename,endcoder,function)

     

    만약 querydata.id = css 가능

    파일 확장자가 있는 파일 이면  id 에 파일 확장자까지 포함해서 넘긴다.

     

     

     

     

     

     

    'CodeingTestPrac' 카테고리의 다른 글

    Node.js - study part 3  (0) 2022.05.13
    Node.js - study part 2  (0) 2022.05.13
    Node-js 그게 뭔디?  (0) 2022.05.06
    3월 10일 ,Flutter const vs final  (0) 2022.03.10
    3월 8일 ,flutter async await  (0) 2022.03.08
Designed by Tistory.