Node 및 javascript 정리

Udemy

Node

Express

javascript

12/04/2020


Node.js

구성

  • npm : Node Packaged Manager, Node.js용 패키지 관리 툴
  • npm_module : npm에 설치된 (로컬)패키지가 저장되는 곳. -g 옵션으로 설치 시 글로벌 패키지 폴더에 저장
  • package.json : node.js의 의존성 패키지 관리 문서

Packages

  • nodemon : node 파일 변경사항을 자동 적용/재실행
  • yargs : node의 command-line argument, interface 관리 편의성 향상. 커맨드를 새로 만들거나 버젼 editing하는데에 사용
  • fs : file system. 기본내장 패키지로 파일을 읽고 쓰는 등의 작업을 수행. 기본적으로 buffer단위로 입출력하므로, binary를 사용

Debugging

debugger 코드를 사용하여 breakpoint를 심어둘 수 있다.
디버깅하기 위해, node inspect <모듈>을 수행한 뒤, chrome://inspect에 접속하여 해당 소스를 열고, 화살표를 눌러가며 breakpoint로 이동한다.
console창에서는 해당 point에서의 변수 등에 접근 할 수 있다.

ES-6

Arrow Function

JAVASCRIPT
const f1 = function(x) {
return x * x
}
const f2 = x => {
return x * x
}
const f3 = () => x * x

위의 세 함수는 모두 같은 역할을 한다. Arrow Function은 이처럼 기존의 function을 간단하게 정의하는데에 사용될 수 있다.
그러나 이 때 Arrow Function의 작동원리에 대해 잘 숙지하자.

JAVASCRIPT
const event = {
name: 'Re-invent day',
printSeminarListByFunc : function() => {
console.log('Seminar list for ' + this.name) // Seminar list for Re-invent day
}
printSeminarListByArrowFunc: () => {
console.log('Seminar list for ' + this.name) // Seminar list for undefined
}
}
event.printSeminarListByFunc()
event.printSeminarListByArrowFunc()

위의 코드에서 일반적인 Function으로 정의한 printSeminarListByFunc와 달리, printSeminarListByArrowFunc는 this.name에 접근이 불가능하다(undefined).
이를 가리켜 Arrow Function은 this를 binding하지 않는다고 말한다.

JAVASCRIPT
const event = {
name: "Re-invent day!",
seminarList: ["Lambda", "Gateway", "CloudWatch"],
// 바로 아래 코드는 function 키워드로 선언하는것과 동일하다.
printSeminarList() {
console.log("Seminar list for " + this.name)
this.seminarList.forEach(function(seminar) {
console.log(seminar + " is presented in " + this.name) // <seminar name> is presented in undefined
})
this.seminarList.forEach(seminar => {
console.log(seminar + " is presented in " + this.name) // <seminar name> is presented in Re-invent day
})
},
}

이러한 특성 덕분에, Arrow Function은 외부의 Context를 그대로 함수에 가져와 수행할 수 있다.

자세한 설명은 해당 문서를 참조하자.
화살표함수 다시 살펴보기

Asynchronous Basics

JAVASCRIPT
console.log("Starting") // 1
setTimeout(() => {
console.log("2 Second Timer") // 2
}, 2000)
setTimeout(() => {
console.log("0 Second Timer") // 3
}, 0)
console.log("Stopping") // 4

위 코드의 출력은 어떤 순서로 진행될까?
1-3-4-2일 것 같지만, 실제로는 1-4-3-2이다. 이는 setTimeout 함수의 Asynchronous적인 특성에서 기인한다.

Call Stack : 실행중인 프로그램(함수)들을 stack에 쌓아둔다 Event Loop : Execute할 준비가 완료된 프로그램들을 대기시켜놓다가, Call Stack이 완전히 비면 수행한다.

Call Stack은 코드 전체를 감싸는 main함수부터 시작하여 console, setTimeout 함수를 Callstack에 쌓는다.
이때 3번은 0초를 대기하므로 즉시 실행할 준비가 되어 Event Loop에 들어가게 된다.

이후 Event Loop에 들어간 3번은 1,4를 감싸는 main 함수가 모두 종료될때까지 기다렸다가 수행된다. 따라서 1-4-(main함수 종료)-3-2 순으로 수행되는것.


WRITTEN BY

알파카의 Always Awake Devlog

Seoul