20220210 TIL

jathazp·2022년 2월 10일
0

1. nodejs 다차원 배열 생성 Array 생성자 이용

function makeArray(size) {
    let arr = new Array(size).fill([]);
    for (let i = 0; i < arr.length; i++) {
        arr[i] = new Array(size).fill('*');
    }
    return arr;
}



2. es6 import / export

//package.json
...
"type":"modules"
...
const exchangeRate = 0.91;

// 안 내보냄
function roundTwoDecimals(amount) {
  return Math.round(amount * 100) / 100;
}

// 내보내기 1
export function canadianToUs(canadian) {
  return roundTwoDecimals(canadian * exchangeRate);
}

// 내보내기 2
const usToCanadian = function (us) {
  return roundTwoDecimals(us / exchangeRate);
};
export { usToCanadian };
// Destructuring
import { canadianToUs } from "./currency-functions";

console.log("50 Canadian dollars equals this amount of US dollars:");
console.log(canadianToUs(50));

// Alias
import * as currency from "./currency-functions";

console.log("30 US dollars equals this amount of Canadian dollars:");
console.log(currency.usToCanadian(30));

3. script 태그 위치?

/body> 위에 넣는게 베스트이다.(body 최하단)

브라우저가 HTML문서를 읽을 때 HTML을 파싱한 다음 DOM 트리를 생성한다. 그런데 브라우저는 HTML 태그들을 읽어나가는 도중 script 태그를 만나면 파싱을 중단하고 javascript 파일을 로드 후 javascript 코드를 파싱한다. 완료되면 그 후에 HTML 파싱이 계속 된다.
이로인해 HTML태그들 사이에 script 태그가 위치하면 두가지 문제가 발생한다.

문제1. HTML을 읽는 과정에 스크립트를 만나면 중단 시점이 생기고 그만큼 Display에 표시되는 것이 지연된다.

문제2. DOM 트리가 생성되기전에 자바스크립트가 생성되지도 않은 DOM의 조작을 시도할 수 있다.

위와 같은 상황을 막기 위해 script 태그는 body 태그 최하단에 위치하는 게 가장 좋다.

ref: https://velog.io/@takeknowledge/script-%ED%83%9C%EA%B7%B8%EB%8A%94-%EC%96%B4%EB%94%94%EC%97%90-%EC%9C%84%EC%B9%98%ED%95%B4%EC%95%BC-%ED%95%A0%EA%B9%8C%EC%9A%94


4. socket 프로그래밍을 이용한 채팅 구현

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    socket.on('chat message', msg => {
        io.emit('chat message', msg);
    });
});

http.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}/`);
});
<!-- <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script>
<title>Hello Socket.io!</title>
</head>
  <body>
    <script>
        const socket = io("localhost:3000");
          socket.on("connect", () => {
          socket.send("Hello!");
        });
          socket.on("message", (data) => {
          console.log(data);
        });
    </script>
  </body>
</html> -->

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
 
 <script src="/socket.io/socket.io.js"></script>
    <script>
     var socket = io();
   
      var messages = document.getElementById('messages');
      var form = document.getElementById('form');
      var input = document.getElementById('input');
   
      form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
      socket.emit('chat message', input.value);
      input.value = '';
      }
      });
   
      socket.on('chat message', function(msg) {
      var item = document.createElement('li');
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
      });
    
   </script>

</head>


  <body>

    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
 
    

  </body>
</html>

ref:
https://socket.io/get-started/chat

https://okayoon.tistory.com/entry/Express-Socketio%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%EC%B1%84%ED%8C%85%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0-2-%ED%86%B5%EC%8B%A0-%EA%B8%B0%EB%B3%B8-%EC%84%B8%ED%8C%85


5.Object

5-1. value값만 뽑기

    const countByUrl = Object.values(socketIdMap);

5-2. key 값만 뽑기

    const countByUrl = Object.keys(socketIdMap);

5-2. object key,value 접근

const ans = Object.entries(o).sort((a, b) => {
  if (a[1] === b[1]) {
      return a[0] > b[0] ? 1 : -1
  }
  return b[1] > a[1] ? 1 : -1
})

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"

6. falthy value

undeined
NaN
0

의 값들은 false와 같은 취급을 받는다.

7. __dirname __filename

__dirname은 현재 실행되는 파일의 파일명을 제외한 경로를 가져옴
https://p-iknow.netlify.app/node-js/path-moudle/

0개의 댓글