2023-01-30 node.js_7

2023. 1. 30. 23:33공부 중/Node.js


 

WEB2 - Node.js - 생활코딩

수업소개 이 수업은 JavaScript를 이용해서 Node.js를 제어해 동적으로 HTML 코드를 생성하는 웹애플리케이션을 만드는 방법에 대한 수업입니다.  수업대상 예를들어 1억개의 페이지로 이루어진 웹사

opentutorials.org

생활코딩 node.js 강의 정리

 


1. 비교연산자 ==와 ===

 

 

=====이 구체적으로 어떻게 다른지 간단한 예시로 알아보자.

 

console.log('1' == 1) //true
console.log('1' === 1) //false

대충 이런 느낌이다.

 

웬만해서는 ===를 사용하길 권한다.

 


2. 콘솔에서 입력받기

 

Node.js에서 콘솔을 통해서 값을 입력하는 방법에 대하여 알아보자.

 

node syntax/conditional.js A B

만약 위와 같이 콘솔에 입력하고 A, B 값을 출력받기를 원한다.

 

그렇다면 프로젝트 파일 아래 syntax/conditional.js 파일을 만들고 아래와 같이 코드를 작성해야 한다.

 

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

 

실행하면 문자열로 이뤄진 배열을 출력한다.

 

process.argv.slice(2)는 문자열로된 배열을 반환한다. (콘솔에서 입력한 값은 모두 문자열로 취급된다.)

 

특히 .slice(2)를 붙인 이유는 process.argv이 기본적으로 문자열 2개를 가지고 있기 때문이다.

 

//코드
var args = process.argv;
console.log(args);
//출력값
❯ node syntax/conditional.js A B
[
  '/usr/local/bin/node',
  '/Users/dmlrms4598/Desktop/nodejs/syntax/conditional.js',
  'A',
  'B'
]
  • argv[0]에는 기본적으로 '/usr/local/bin/node' (= Node.js 런타임이 위치한 경로)를 저장한다.
  • argv[1]에는 기본적으로 '/Users/dmlrms4598/Desktop/nodejs/syntax/conditional.js' (= 실행한 파일이 위치한 경로)를 저장한다.

따라서 순수하게 입력한 문자열 AB만을 원한다면 .slice(2)를 붙인다.

 

참고로 argv는 argument values를 args는 arguments를 뜻한다.

 


참고. process 객체

 

The process object provides information about, and control over, the current Node.js process.

 

process 객체는 해당 node.js 프로세스에 관한 정보와 제어를 제공하는 전역 객체다.

 

별도로 import 할 필요가 없으며 어디서든 접근할 수 있다.

 


3. style.css와 color.js 오류 해결

 

참고 포스팅 : https://www.sololearn.com/discuss/2209052/css-doesn-t-load-into-my-html-code-using-node-js

 

CSS doesn't load into my HTML code using NODE.js | Sololearn: Learn to code for FREE!

When i read files from node js its not reading css files. and also I want to mention that my css files are connected to html, when I run it on it own its showing it

www.sololearn.com

 

참고 포스팅 : https://stackoverflow.com/questions/38295722/how-do-you-serve-css-in-a-node-js-application

 

How do you serve CSS in a node.js application

I've been messing around with node.js and I can't seem to serve my CSS properly. Before, I had it embedded in my HTML in the header under a tag, but now I'm trying to learn how to serve it as a se...

stackoverflow.com

 

node.js를 사용하기 시작하면서 이전에 동작하던 css와 js가 말썽이다.

 

심지어는 이미지도 보이지 않는다.

 

 

일단 개발자 도구를 이용해서 network를 확인한다.

 

무슨 일이 있었는지 확인해 보자.

 

웹 브라우저에서 http://localhost:300/?id=black%20tea라는 request url을 보낸 이후에 추가로 http://localhost:300/style.css, http://localhost:300/color.js, http://localhost:300/black_tea.jpeg request url을 추가로 보낸 것을 확인할 수 있다.

 

문제는 우리 main.js에서는 아직 이들을 정상적으로 처리하지 못한다.

 

지금의 main.js에서는 아래와 같다.

 

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'){
        response.writeHead(404);
        response.end();
        return;
    }

    response.writeHead(200);
    fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description) {
      var template = `
        <!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>WEB - ${title}</title>
            <link rel="stylesheet" href="style.css">
            <script src="color.js"></script>
          </head>
          <body>
            <div id="top">
              <h1><a href="/">차</a></h1>
              <input type="button" value="night" onclick="nightDayHandler(this)"/>
            </div>
            <div id="grid">
              <ul>
                <li><a href="/?id=black%20tea">홍차</a></li>
                <li><a href="/?id=oolang%20tea">우롱차</a></li>
                <li><a href="/?id=green%20tea">녹차</a></li>
              </ul>
              <div id="article">${description}</div>
            </div>
          </body>
        </html>
      `;
      response.end(template);
    });
});
app.listen(3000);

이미 var queryData = url.parse(_url, true).query; 여기서부터 문제가 생겼다.

 

실제로 console.log(queryData);를 찍어보면 queryData의 값이 없다.

 

 

data/undifined 같은 실제로 존재하지 않는 파일을 읽어다가 template를 완성시켜 response.end(template); 해주고 있을 것이다.

 

 

그렇기에 실제로 브라우저가 받은 response의 source를 열어다 보면 아래와 같다.

 

<!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <title>WEB - undefined</title>
            <link rel="stylesheet" href="style.css">
            <script src="color.js"></script>
          </head>
          <body>
            <div id="top">
              <h1><a href="/">차</a></h1>
              <input type="button" value="night" onclick="nightDayHandler(this)"/>
            </div>
            <div id="grid">
              <ul>
                <li><a href="/?id=black%20tea">홍차</a></li>
                <li><a href="/?id=oolang%20tea">우롱차</a></li>
                <li><a href="/?id=green%20tea">녹차</a></li>
              </ul>
              <div id="article">undefined</div>
            </div>
          </body>
        </html>

현재 웹 브라우저에 style.css, color.js, black_tea.jpeg를 정상적으로 적용하기 위해서는 http://localhost:300/style.css, http://localhost:300/color.js, http://localhost:300/black_tea.jpeg request url에 대하여 올바른 file을 reponse해주는 코드를 추가로 작성해야 한다.

다음과 같은 코드를 fs.readFile(data/${queryData.id}, 'utf8', function(err, description) {..} 위에 추가하면 된다.

 

if(_url == '/style.css'){
      response.writeHead(200, {'Content-type' : 'text/css'});
      var fileContents = fs.readFileSync('style.css', 'utf-8');
      response.end(fileContents);
    };

    if(_url == '/color.js'){
      response.writeHead(200, {'Content-type' : 'text/js'});
      var fileContents = fs.readFileSync('color.js', 'utf-8');
      response.end(fileContents);
    };

여러 가지를 실험해 보니깐 readFileSync와 그 값을 변수에 대입하는 것 이 두 가지 조건을 만족해야 정상적으로 동작했다. (왜 그런진 모르겠다. 동기화의 문제로 추측한다.)

 

 

계속해서 찾아보며 알게 된 사실이 있다.

 

보통은 CSS와 JS 파일을 이런 방식으로 전달하진 않는다.

 

정상적인 방법은 Express.js라는 프레임워크로 해결하는 것이다.

 

그러니 크게 신경 쓸 필요 없이 재미로 보고 넘겨도 될 것 같다.

 


'공부 중 > Node.js' 카테고리의 다른 글

2023-02-11 node.js_9  (0) 2023.02.11
2023-01-31 node.js_8  (0) 2023.01.31
2023-01-23 node.js_6  (0) 2023.01.23
2023-01-23 node.js_5  (0) 2023.01.23
2023-01-22 node.js_4  (0) 2023.01.22