2018 Mad camp/기술

[Node.js]생활코딩 필기

goakgoak 2019. 1. 3. 20:16

1/03


수업의 목표

node.js로 만드는 node.js web application을 만드는 것, 따라서 과정마다 node.js runtime이 가지고 있는 기능 실행하면서 node.js가 가지고 있는 기능으로 node.js application을 하나씩 완성

그 조작 장치는 JavaScript 라는언어

수업의 목적

이전에는 웹페이지의 소유자만이 컨텐츠를 추가할 수 있었음

귀찮고 반복적인 html의 작성방법을 기계에게 맡기기 위해 출현한 기술

문서로 시작했던 web이 app으로 변화, 웹브라우저에 갇혀있는 편파적인 언어 Javascript (?)

태초의 javascript가 웹브라우저를 제어하는 것 이였다면

node.js 는 웹브라우저를이용하여 javascript가 아닌 컴퓨터 자체를 제어한다.

설치

웹브라우저 상에서 돌아가는 웹 어플리케이션 만들기 위해서는

웹브라우저가 가지고 있는 여러가지 기능들 중에서(제목 표시, 목록 표시) 우리가 만들고자 하는 웹 애플리케이션에 필요한 기능들을 어떠한 컴퓨터 언어의(HTML) 문법에 따라서 웹 애플리케이션을 구축한다.

node.js도 마찬가지로 프로그램을 다운받아서 설치, node.js runtime 이라는 프로그램에서 웹브라우저에서 그러했던 것 처럼 javascript라는 언어로 node.js runtime이 가지고 있는 기능 중에 우리가 필요한 것들을 호출하는 과정에서 node.js 어플리케이션을 만들 수 있게된다.

web application             node.js application
html -> JavaScript
web browser Node.js runtime
  • windows

    • cmd > node

    • JavaScript 문법 이용해서 node.js가 가지고 있는 기능 실행해보기

      console.log(1+1); // ()안에 있는 계산 결과를 화면에 출력 : 2
    • 나갈 때는 ctrl + c 두번

    • 파일에 미리 명령어 저장해놓고 사용하는 방법

      1. atom editor 사용해서 .js 파일 만들기

      2. cmd > nodejs 디렉토리로 이동

        cd C:\Users\q\Desktop\nodejs
      3. helloworld.js 파일 실행

        C:\Users\q\Desktop\nodejs> node helloworld.js // 2 출력

순서

  1. 먼저 node.js runtime을 각자의 운영체제에 설치

  2. JavaSctript라는 컴퓨터 언어로 node.js runtime을 실행하기

  3. 우리가 만들고자 하는 node.js application을 어떻게 만드는 것인가? 에 대한 공부

node.js로 웹서버 만들기

웹브라우저에 주소 입력해서 요청하면 웹서버는 요청에 따른 정보를 찾아서 응답해주는 관계

node.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'){
     return response.writeHead(404);
  }
   response.writeHead(200);
   console.log(__dirname + url);
   response.end(fs.readFileSync(__dirname + url));

});
app.listen(3000);

console

C:\Users\q\Desktop\nodejs/index.html 
// 실습파일의 main.js가 위치하는 경로에 index.html이 전달됨

사용자가 접근할 때 마다 JavaScript를 통해 우리가 읽을 파일을 만들어 파일로 읽음

node.js가 경로에 해당하는 파일을 읽어서 가져옴. response.end()안에 위치시킴

node.js는 ()안에 어떤 코드를 넣느냐에 따라 사용자에 전송하는 데이터가 바뀐다.

response.end('sangeuni : ' + url);

아파치는 할 수 없지만 node.js 장고 php는 가능한 일 들이다.

프로그래밍적으로 사용자에게 전송할 데이터를 생성한다. 라는 것이 node.js가 가지고 있는 힘 !

root@CS496-9:~# mkdir myapp
root@CS496-9:~# cd ./myapp/
root@CS496-9:~/myapp# npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (myapp)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /root/myapp/package.json:

{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}


Is this ok? (yes)
root@CS496-9:~/myapp# ls
package.json
root@CS496-9:~/myapp# vim ./index.js
varoot@CS496-9:~/myapp# cat index.js
var Express = require('express');
var App = Express();

App.get('/', function(req, res) {
  res.end('Hello, World!');
});

App.listen(80, function() {
  console.log('Server is listening on port 80');
});
root@CS496-9:~/myapp# nodejs index.js
Server is listening on port 80
^C
root@CS496-9:~/myapp#