response.writeHead(200);
response.end(template);

위 코드는 if (pathname === '/'){ ... } 안에 있는 코드이고

else 부분에는 다음의 코드를 넣는다. 

response.writeHead(404);
response.end('Not Found');

200 : 200이라는 숫자를 서버가 브라우저에게 주면 "파일을 성공적으로 전송함"

404 : 파일을 찾을 수 없는 경우, 웹 서버는 404라는 약속된 번호를 준다. 

 

<전체 코드>

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 pathname = url.parse(_url, true).pathname;
    var title = queryData.id;
 
    if(pathname === '/'){
      fs.readFile(`data/${queryData.id}`, 'utf8', function(err, 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.writeHead(200);
        response.end(template);
      });
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
 
 
 
});
app.listen(3000);

 

 

Input and Output

 

Input 

Parameter : 입력되는 정보의 형식

Argument : 그 형식에 맞게 실제로 입력한 값

 

Output

console화면, html, 파일 저장, 등

 

"nodejs console input parameters"' 검색

https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program

 

How do I pass command line arguments to a Node.js program?

I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this: $ node server.js folder h...

stackoverflow.com

// syntax 폴더 안에 conditional.js 파일
var args = process.argv;
console.log(args);

node syntax\conditional.js egoing

실행시켜 출력하면 ['..','...','egoing'] 이 출력됨 

 

☆ 1부터 counting하지 않고 0부터 counting함

0번 자리 : nodejs runtime의 위치

1번 자리 : 실행시킨 파일의 경로

2번 자리 : 사용자가 입력한 입력값

 

node syntax\conditional.js egoing k0214

실행시켜 출력하면 ['...', '...', 'egoing', 'k0214'] 이 출력됨

 

var args = process.argv;
console.log(args[2]);

if(args[2]=='1'){
    console.log('C1'); 
 }
else{
     console.log('C2');
 }

args[2] 는 배열의 2번 자리(사용자가 입력한 입력값) 을 의미

 

data 폴더를 생성하고 그 안에 CSS,HTML,JavaScript 라는 이름의 파일(txt)를 생성한다. 

파일 안에 각각의 내용을 저장한다. 

<기존의 main.js> 동적 웹페이지

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;
    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>
      <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><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);

 

main.js 를 수정한다. 

fs.readFile 부분 작성 

`data/${queryData.id}` : file 이름 (data directory 밑에 있는 ${queryData.id} (쿼리스트링에 따라 파일명 생성) ) 

var template= `..` 부분을 fs.readFile{ } 안에 넣는다. 

template=` ` 안에 있는 <p>...</p> 부분을  <p>${description}</p> 로 변경한다. 

description 은 변수로 사용되는데, file에 있는 내용을 저장하고 있는 변수이다. 

    fs.readFile(`data/${queryData.id}`, 'utf8', function(err, 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);
    })
});

 

 

<전체코드>

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;
    if(_url == '/'){
      title = 'Welcome';
    }
    if(_url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    fs.readFile(`data/${queryData.id}`, 'utf8', function(err, 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

- 정보시스템에서 가장 먼저 알아야 할 것 : Create, Read 

Create, Read (50%) + 수정 삭제 (25%) + 엄청난 에너지 노력(25%)

 

" node.js file read "  - Node.js 로 파일을 읽고 싶을 때 검색 keyword

node.js 홈페이지에서 nod.js가 제공하는 모듈 중 "file system"

https://nodejs.org/dist/latest-v6.x/docs/api/fs.html

 

File System | Node.js v6.17.1 Documentation

File System# File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require('fs'). All the methods have asynchronous and synchronous forms. The asynchronous form always takes a completion callback as its last argumen

nodejs.org

ctrl+f 키를 눌러 "readFile" 을 검색하면 아래와 같은 화면이 나오는데, 이를 참고하여 코드를 짜고 공부하면 된다. 

"nodejs공부" 폴더 안에 "nodejs"폴더를 만들고 fileread.js 와 sample.txt를 생성

node fileread.js

var fs = require('fs');
fs.readFile('sample.txt',function(err,data){
    console.log(data);
});

sample.txt에는 아무 내용이나 넣었다. 

 

cmd창에서 

cd nodejs공부폴더 

node fileread.js를 실행시키니 다음과 같은 에러가 떴다.(loader.js:969  Error: Cannot find module)

sample.txt가 저장되어있는 nodejs폴더가 아닌 상위폴더에서 node 실행시켰기 때문에 sample.txt를 찾지 못해 생긴 에러이다. 

해당 파일이 있는 폴더로 가서 node실행시키면 결과가 나옴

 

 

<정적 웹 페이지>

저장된 그대로 웹 페이지에 보이는 것

<!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>

 

<동적 웹 페이지>

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;
    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>
      <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><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);

동적인 웹페이지를 만들기 위해 template 변수 생성 -> template literals(``) 를 사용해서 html 코드를 넣음

query string에 따라 바뀌었으면 하는 부분에 ${queryData.id}로 대체

 

 

URL의 이해

http://opentutorials.org:3000/main?id=HTML&page=12

 

http : protocol 통신규칙. 사용자가 서버에 접속할 때 어떤 방식으로 서버에 접속할 것인지에 대한 부분. 웹브라우저가 웹서버와 서로 데이터를 주고받기 위해 만든 통신 규칙

opentutorials.org : domain(host) . 인터넷에 접속되어 있는 각각의 컴퓨터를 가리키는 주소

3000 : port 번호. 한개의 컴퓨터 안에 여러 대의 서버가 있을 수 있는데, 클라이언트가 접속했을 때 그 중에 3000번 서버에 연결한 것

main : path. 그 컴퓨터 안에 있는 어떤 디렉토리의 어떤 파일인지 가리킴

id=HTML&page=12 : query string. 이 값을 변경하면 웹서버에 데이터를 전달할 수 있음. 쿼리스트링의 시작은 ?임. 값의 이름과 값은 = 로 구분

 

 

URL을 통해서 입력된 값을 사용하는 방법

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);
    response.end(fs.readFileSync(__dirname + url));
 
});
app.listen(3000);

 

 

 

 

위 코드의 경우 : cmd창에서 파일을 실행시킨 후에 http://localhost:3000/을 주소창에 입력하면 된다. 

 

사용자가 주소를 입력 할 때, 쿼리스트링 부분에 다른 값이 들어올 때마다 그에 맞춰서 데이터를 보여 주어야할때

" node.js url parse query string " 검색 참고

즉, cmd 창에서 파일을 실행 시킨 후에 http://localhost/?id=HTML를 입력했을 시 그에 맞춰 데이터를 보여주어야 함

 

쿼리스트링 부분이 반영되는 코드 

var url = request.url;

console.log(url); 을 저 코드 밑에 넣어 확인 해 보면 /?id=HTML 이라는 값이 url 변수에 담겨진 것을 확인할 수 있음

( id값이 CSS라면 url 변수에는 /?id=CSS 가 대입되어있음)

 

아래의 코드를 추가 (의미 : "url이라는 모듈을 url이라는 변수를 이용하여 사용할 것" )

var url = require('url');

 

변수 url이 겹치므로 수정해 줄것 

var _var = request.url;

 

_url 변수에 들어온 쿼리스트링 값을 이용하기 위해 분석(parse)를 해주는 코드 작성 -> queryData 변수에 대입

여기서 HTML이라는 값을 얻으려면 queryData.id를 입력하면 됨

var queryData = url.parse(_url, true).query;
console.log(queryData);
console.log(queryData.id);

 

사용자가 접속한 url에 따라 해당하는 파일들을 읽어주는 코드 대신 화면에 HTML 혹은 CSS가 출력되도록 수정(쿼리스트링에 따라 다르게 동작)

//response.end(fs.readFileSync(__dirname + _url));
response.end(queryData.id);

 

전체 코드

 

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);
    response.end(queryData.id);
 
});
app.listen(3000);

1. Number Data type

이항연산자 - 왼쪽(좌항)에 있는 값과 오른쪽(우항)에 있는 값을 처리해서 하나의 값을 만들어내는 역할

console.log(1);
console.log(1+1);
console.log(4-1);
console.log(2*3);
console.log(10/2);

 

2. String Data type

String(문자열) 표현 : " " , ' '

 

어떤 데이터를 사용하냐에 따라 연산자의 의미가 바뀜 

"+" 이항연산자 -> 결합 연산자 

//이항 연산자 
console.log(1+1); 	// 2

//결합 연산자 
console.log('1'+'1');	// 11

 

 

String count

string.length  

console.log('abcd'.length);

 

3. Variable

var a = 1;
console.log(a);

변수 선언시 변수 앞에 var 를 붙이는 것이 좋음 

 

 

코드 상에서의 줄바꿈 

\

출력 상에서의 줄바꿈

\n

var name = 'k8805';
// String literals
var letter = 'Dear '+name+'\n\nabcdefg'+'\
\
abc';
console.log(letter);

 

4. Template literals

키보드를 보면 ~ 표시 옆에 ` 가 있는데 이를 이용

var letter = `Dear ${name}

abcdefg`;
console.log(letter);

개행문자 \n를 사용하지 않고 enter를 쳐도 error없이 출력됨

 

변수를 넣어서 치환하고 싶을 때

 +name+ 대신에 ` ` 안에서 ${name}을 사용함

`${1+1}` 의 경우 1+1 의 연산결과가 출력됨

 

※ 5번 6번 7번 세가지는 서로 밀접한 관계에 있기 때문에 같이 생각하는 것이 좋음

5. Boolean Data type

console.log(true);
console.log(false);

실행하면 각각 true와 false가 출력된다. 

true는 변수 이름으로 쓸 수 없음 

 

6. Comparison operator (비교연산자)

좌항과 우항을 비교해서 true나 false 둘 중에 하나의 값을 만들어내는 연산자 

console.log(1==1);  //true
console.log(1==2);  //false
console.log(1===1); //true
console.log(1>2);   //false
console.log(1<2);   //true

'=' 는 개수에 따라 의미가 다름

= 1개 (name=1) : 대입 연산자

= 2개 (name==1) : 비교 연산자 (좌항과 우항의 값이 같으면 true, 다르면 false)

= 3개 (name===1) : 비교 연산자 ( 좌항과 우항의 값이 정확하게 같은지 비교해주는 연산자)

☆ 비교연산자를 사용할 때, == 보다는 === 권장

 

7. Conditional Statement (조건문)

조건에 따라 실행문의 흐름 제어

if 괄호 안에는 문법적으로 true/false 즉, boolean형이 들어감

if(true){
   console.log('C1'); 
}
if(false){
    console.log('C2');
}

위 코드와 아래의 코드는 동일하다.  true가 아니면 false이기 때문에  if (true){..} else{..} 를 쓸 수 있다. 

if(true){
    console.log('C1'); 
 }
else{
     console.log('C2');
 }

 

8. loop (반복문)

for문, while문, do-while문

- while문 (가장 기초적이지만 불편) 

while 괄호 안에는 if 괄호 안과 마찬가지로 boolean형을 넣는다. 

while 괄호 안에 true를 넣으면 : 무한 반복문 

아래 코드와 같이 i<5를 넣으면 반복문이 실행될때 마다 i가 1씩 커지고, i가 5가 되면 false가 되므로 반복문을 종료한다. 

var i=0;
while(i<5){
    console.log(i);
    i=i+1;
}

 

'Web > HTML\CSS\JavaScript' 카테고리의 다른 글

[JavaScript] Function  (0) 2020.07.25
[JavaScript] Array data type  (0) 2020.07.25
[HTML] 기본문법 태그  (0) 2020.07.13
[HTML+CSS3] 링크만들기  (0) 2020.05.25
[HTML+CSS3] 이미지삽입하기  (0) 2020.05.19

https://nodejs.org/en/

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

 

1. 위 네모 박스를 클릭해 설치한 후소스파일을 저장할 폴더를 만든다. 

 

2. Visual Code 를 이용하여 .js 파일을 생성후 작성한다. 

ex) 

console.log(1+1); 의 의미는 1+1 의 연산결과를 console창에 출력한다는 것을 의미한다.

 

3. Ctrl + R 키를 눌러 cmd창을 열고 해당 파일이 저장된 폴더로 이동한다. 

( cd 경로 ) 를 입력하면 됨

 

4. dir 를 입력하면 폴더 안에 어떤 파일이 있는지 확인할 수 있다. 

 

5. node 파일이름.js 를 입력하면 해당 파일에 작성한 코드의 실행결과를 출력하여 준다. 

 

+ Recent posts