[Node.js]자바스크립트

Enter·2021년 7월 23일
0

Node.js

목록 보기
3/3

📖ES2015+ 최신 문법


📌const, let

var
▪ 함수 스코프(범위)를 가지므로 if문에 관계없이 접근 가능.

if(true){
   var x = 3;
}
console.log(x);	//3

const
▪ 블록 스코프를 가지므로 블록 밖에서는 변수에 접근 불가능.
▪ 한 번 값을 할당하면 다른 값을 할당할 수 없음. (다른 값을 할당하려고 하면 에러 발생.)
▪ 초기화할 때 값을 할당하지 않으면 에러 발생.
▪ const로 선언한 변수 = 상수

if(true){
  const y = 3;
}
console.log(y)	// Uncaught ReferenceError: y in not defined

let
▪ 블록 스코프를 가지므로 블록 밖에서는 변수에 접근 불가능.

-> 변수 선언시 기본적으로 const사용. 다른 값을 할당해야 할 때 let 사용.


📌템플릿 문자열

▪ 큰따옴표나 작은따옴표로 감싸는 것이 아니라 `으로 감쌈.
▪ 문자열 안에 변수를 넣을 수 있음.
▪ ${변수} 형식으로 변수를 더하기 기호 없이 문자열에 넣을 수 있음.

ex)
기존 ES5문법

var num1 = 1;
var num2 = 2;
var result = 3;
var string1 = num1 + ' 더하기 ' + num2 + ' 는 \'' + result + '\'';
console.log(string1);	// 1 더하기 2는 '3'

ES2015문법

const num3 = 1;
const num4 = 2;
const result2 = 3;
const string2 = `${num3} 더하기 ${num4}는 '${result}'`;
console.log(string2);	// 1 더하기 2는 '3'

📌객체 리터럴

▪ 객체의 메서드에 함수를 연결할 때 콜론과 function을 붙이지 않아도 됨.
▪ 속성명과 변수명이 동일한 경우 한 번만 써도 됨.
▪ 객체 리터럴 안에 동적 속성을 선언해도 됨.

ex)
기존 코드

var sayNode = function(){
   console.log('Node');
};
var es = 'ES';
var oldObject = {
   sayJS:function(){
      console.log('JS');
   },
   sayNode: sayNode,
};
oldObject[es+6] = 'Fantastic';
oldObject.sayNode();	//Node
oldObject.sayJS();	//JS
console.log(oldObject.ES6);	//Fantastic

바뀐 코드

const newObject = {
  sayJS(){
    console.log('JS');
  },
  sayNode,
>   [es+6]: 'Fantastic',
};
newObject.sayNode();	//Node
newObject.sayJS();	//JS
console.log(newObject.ES6);	//Fantastic

📌화살표 함수

▪ function 선언 대신 => 기호로 함수 선언.
▪ 변수에 대입하면 나중에 재사용 가능.
▪ 화살표 함수에서 내부에 return문 밖에 없는 경우 return문 줄일 수 있음.

function add1(x, y){
   return x+y;
}
const add2 = (x, y) => {
  return x+y;
};
const add3 = (x, y) => x+y;
const add4 = (x, y) => (x+y);

function not1(x){
  return !x;
}
const not2 = x => !x;

▪ 기본적으로 화살표 함수를 쓰되, this를 사용해야 하는 경우 화살표 함수와 함수 선언문(function)중 하나를 골라 사용.

//---------중략----------
   //함수 선언문
   logFriends: function(){
     var that = this;	//relationship1을 가리키는 this를 that에 저장.
     this.friends.forEach(function (friend){
       console.log(that.name, friend);
     });
   },
//---------중략----------
  //화살표 함수
  logFriends(){
     this.friends.forEach(friend => {
       console.log(that.name, friend);
     });
   },
}

📌구조분해 할당

▪ 구조분해 할당을 사용하면 객체와 배열로부터 속성이나 요소를 쉽게 꺼낼 수 있음.
▪ 함수의 this가 달라질 수 있음.

ex)객체의 속성을 같은 이름의 변수에 대입하는 코드

var candyMachine = {
  status:{
    name: 'node',
    count: 5,
  },
  getCandy: function(){
    this.status.count--;
    return this.status.count;
  },
};
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;

바뀐 코드

const candyMachine = {
  status:{
    name: 'node',
    count: 5,
  },
  getCandy(){
    this.status.count--;
    return this.status.count;
  },
};
const { getCandy, status: {count} } = candyMachine;

ex)배열에 대한 구조분해 할당

var array = ['nodejs', {}, 10, true];
var node = array[0];
var obj = array[1];
var bool = array[3];

바뀐 코드

const array = ['nodejs', {}, 10, true];
const [node, obj, ,bool] = array;

📌클래스

▪ 클래스 문법이 추가되었지만 프로토타입 기반 문법을 보기 좋게 클래스로 바꾼 것이라 이해해야 함.

ex) 프로토타입 상속 예제

var Human = function(type){
  this.type = type || 'human';
};

Human.isHuman = function(human){
  return human instanceof Human;
}

Human.prototype.breathe = function(){
  alert('h-a-a-a-m');
};

var Zero = function(type, firstName, lastName){
  Human.apply(this, arguments);
  this.firstName = firstName;
  this.lastName= lastName;
}

Zero.prototype = Object.create(Human.prototype);
Zero.prototype.constructor = Zero;	//상속하는 부분
Zero.prototype.sayName = function(){
  alert(this.firstName + ' ' + this.lastName);
};
var oldZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(oldZero);	//true

클래스 기반으로 바뀐 코드

class Human{
  constructor(type = 'human'){
    this.type = type;
  }
  
  static isHuman(human){
    return human instanceof Human;
  }
  
  breathe(){
  	alert('h-a-a-a-m');
  }
}

class Zero extends Human{
  constructor(type, firstName, lastName){
    super(type);
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  sayName(){
    super.breathe();
    alert(`${this.firstName} ${this.lastName}`);
  }
} 
const newZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(newZero);

📌프로미스

▪ 자바스크립트와 노드의 API들이 콜백 대신 프로미스 기반으로 재구성.
▪ 실행은 바로 하되 결괏값은 나중에 받는 객체.

const condition = true;	//true면 resolve, false면 reject
const promise = new Promise((resolve, reject) => {
  if (condition) {
    resolve('성공');
  } else {
    reject('실패');
  }
});
//다른 코드가 들어갈 수 있음
promise
  .then((message) => {
    console.log(message);	//성공(resolve)한 경우 실행
  })
  .catch((error) => {
    console.error(error);	//실패(reject)한 경우 실행
  })
  .finally(() => {	//끝나고 무조건 실행
    console.log('무조건');
  });

▪ 프로미스 내부에서 resolve가 호출되면 then이 실행되고, reject가 호출되면 catch가 실행됨. finally은 성공/실패 여부와 상관없이 실행됨.
▪ resolve와 reject에 넣어준 인수는 각각 then과 catch의 매개변수에서 받을 수 있음.
▪ 결과값은 실행이 완료된 후 then이나 catch 메소드를 통해 받음.
▪ new Promise는 바로 실행되지만, 결과값은 then을 붙였을 때 받음.
▪ then이나 catch에 다른 then이나 catch를 붙일 수 있음. 이전 then의 return 값을 다음 then의 매개변수로 넘김.


const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
Promise.all([promise1, promise2])
   .then((result) => {
     console.log(result);	//['성공1', '성공2'];
   })
   .catch((error) => {
    console.error(error);
   });

▪ Promise.resolve는 즉시 resolve하는 프로미스를 만드는 방법. (즉시 reject하는 Promise.reject도 있음.
▪ 프로미스가 여러 개 있을 때 Promise.all에 넣으면 모두 resolve될 때까지 기다렸다가 then으로 넘어감.
▪ result 매개변수에 각각의 프로미스 결괏값이 배열로 들어 있으며 Promise 중 하나라도 reject가 되면 catch로 넘어감.


📌anync/await

▪ for문과 async/awaot을 같이 써서 프로미스를 순차적으로 실행할 수 있음.
▪ async 함수의 반환값은 항상 Promise로 감싸짐.
▪ 중첨되는 콜백 함수가 있을 때 프로미스를 거쳐 async/await을 사용하면 코드가 간결해짐.

ex)
콜백 - > 프로미스

function findAndSaveUser(Users){
  Users.findOne({})
   .then((user) => {
     user.name = 'zero';
     return user.save();
   })
   .then((user) => {
     return users.findOne({ gender: 'm' });
   })
   .then((user) => {
     //생략
   })
   .catch(err => {
     console.error(err);
   });
}

프로미스 -> async/await

async function findAndSaveUser(Users){
  try{
    let user = await Users.findOne({});
    user.name = 'zero';
    user = await user.save();
    user = await Users.findOne({ gender: 'm'});
    //생략
  }catch(error){
    console.error(error);
  }
}



📖프런트엔드 자바스크립트


📌AJAX

▪ 비동기적 웹 서비스를 개발할 때 사용하는 기법.
▪ 페이지 이동 없이 서버에 요청을 보내고 응답을 받는 기술.
▪ AJAX 요청은 jQuery나 axios 같은 라이브러리를 이용해서 보냄.
▪ 프론트엔드에서 사용하려면 HTML 파일을 하나 만들고 그 안에 script 태그를 추가해야 함.

<script src="http://unpkg.com/axios/dist/axios.min.js"></script>
<script>
  //여기에 에제 코드를 넣으세요.
</script>

Get 방식 요청 예제

axios.get('https://요청을 보낼 주소')
  .then((result) => {
    console.log(result);
    console.log(result.data);	//{}
  })
  .catch((error) => {
    console.error(error);
  });

▪ axios.get 내부에 new Promise가 들어 있으므로 then과 catch 사용 가능.
▪ result.data에는 서버로부터 보낸 데이터가 들어있음.
▪ 프로미스이므로 async/await 방식으로 변경 가능.

Post 방식 요청 예제

(async () => {
  try {
    const result = await axios.post('https://요청을 보낼 주소', {
      name: 'zerocho',
      birth: 1994,
    });
    console.log(result);
    console.log(result.data);	// {}
  }catch(error){
    console.error(error);
  }
})();

▪ Post 요청에서는 데이터를 서버로 보낼 수 있음.
▪ GET 요청이면 axios.get을 POST 요청이면 axios.post를 사용.
▪ GET 요청과 POST 요청이 두 번째 인수로 데이터를 넣어 보내는 것이 다름.


📌FormData

▪ HTML form 태그의 데이터를 동적으로 제어할 수 있는 기능.
▪ 주로 AJAX과 함께 사용.

const formData = new FormData();
formData.append('name', 'zerocho');
formData.append('item', 'orange');
formData.append('item', 'melon');
formData.has('item');	//true
formData.has('money');	//false;
formData.get('item');	//orange
formData.getAll('item');	//['orange', 'melon'];
formData.append('test', ['hi', 'zero']);
formData.get('test');	//hi, zero
formData.delete('test');
formData.get('test');	//null
formData.set('item', 'apple');
formData.getAll('item');	//['apple'];

▪ 생성된 객체의 append 메서드로 키-값 형식의 데이터를 저장할 수 있음.
▪ append 메서드를 여러 번 사용해서 키 하나에 여러개의 값을 추가해도 됨.
▪ has 메서드는 주어진 키에 해당하는 값이 있는지 여부를 알림.
▪ get 메서드는 주어진 키에 해당하는 값 하나를 가져옴.
▪ getAll 메서드는 해당하는 모든 값을 가져옴.
▪ delete 메서드는 현재 키를 제거하는 메서드.
▪ set 메서드는 현재 키를 수정한느 메서드.

▪ axios로 폼 데이터를 서버에 보낼 때 두 번째 인수에 데이터를 넣어 보냄.

const result = await axios.post('https://요청을 보낼 주소', formData);

📌encodeURIComponent, decodeURIComponent

encodeURIComponent
▪ 서버가 한글 주소를 이해하지 못하는 경우 사용.
▪ 한글 주소 부분만 encodeURIComponent 메서드로 감쌈.
▪ 브라우저뿐만 아니라 노드에서도 사용 가능.

const result = await axios.get(`https://www.zerocho.com/api
search/${encodeURIComponent('노드')}`);

decodeURIComponent
▪ 받는 쪽에서는 decodeURIComponent 사용.
▪ 브라우저뿐만 아니라 노드에서도 사용 가능.

decodeURIComponent('%EB%85%B8%EB%93%9C');  //노드

📌데이터 속성과 dataset

▪ 노드를 웹 서버로 사용할 경우, 프런트엔드에 데이터를 내려보낼 때 보안과 관련된 민감한 데이터는 내려보내지 말아야 함.

데이터 속성
▪ 아래와 같이 HTML 태그의 속성으로 data-로 시작하는 것들을 의미.
▪ 자바스크립트로 쉽게 접근할 수 있다는 장점이 있음.
▪ script 태그를 보면 dataset 속성을 통해 li 태그의 데이터 속성에 접근. (데이터 속성 이름에 변형이 있음. dataset에 데이터를 넣어도 HTML 태그에 반영됨.)

<ul>
  <li data-id="1" data-user-job="programmer">Zero</li>
  <li data-id="2" data-user-job="designer">Nero</li>
  <li data-id="3" data-user-job="programmer">Hero</li>
  <li data-id="4" data-user-job="ceo">Kero</li>
</ul>
<script>
  console.log(document.querySelector('li').dataset);
    //{id: '1', userJob: programmer'}
 </script>






📒Node.js 교과서 개정2판 책을 참고하여 작성하였습니다.

https://www.gilbut.co.kr/book/view?bookcode=BN002827

profile
Cherish the moment :)

0개의 댓글