개발언어/Node.js
-
NodeJS - Promise, async/await개발언어/Node.js 2023. 3. 27. 15:51
Promise function findAndSaveUser(Users) { Users.findOne({}) .then((user) => { user.name = "surge100"; return user.save(); }) .then((user) => { return Users.findOne({ gender: "m" }); }) .then((user) => { //생략 }) .catch((err) => { console.error(err); }); } Promise.all(배열): 여러 개 의 프로미스를 동시에 실행 하나라도 실패하면 catch로 간다. allSettled로 실패한 것만 추려낼 수 있다. 콜백 헬이라고 불리는 지저분한 자바스크림트 코드의 해결책 프로미스 : 내용이 실행은 되었지만 결과를 ..
-
NodeJS - 모듈(import, export default)개발언어/Node.js 2023. 2. 20. 11:52
ECMAScript모듈 ES모듈은 공식적인 자바스크립트 모듈형식이다. 노드에서 아직까지는 CommonJS모듈을 많이 쓰긴 하지만, ES모듈이 표준으로 정해지면서 점점 ES모듈을 사용하는 비중이 늘어나고 있습니다. 브라우저에서도 ES모듈을 사용할 수 있어 브라우저와 노드 모두에 같은 모듈형시을 사용할 수 있다는 것이 장점이다. CommonJS모듈은 공식 모듈이 아니라 표준 묘듈에 가까웠다. 사실 표준 모듈이라고 단언하기도 어려운 점이 JavaScrip자체이 표준이 없었기 때문에 노드생태계 에서는 CommonJS라는 자체적인 표준을 정해서 사용하고 있었던 것이다. 하지만 브라우저 쪽에서 먼저 ES 모듈이 표준모듈로 정해지면서 노드에서도 ES모듈을 많이 사용하는 추세이다. 또한 장기적인 관점에서 모면 Comm..
-
NodeJS - 내장 객체 알아보기(this, require)개발언어/Node.js 2023. 2. 20. 09:51
const checkNumber = require("./func"); const { odd, even } = require("./var"); function checkStringOddEven(str) { if (str.length % 2) { return odd; } else { return even; } } console.log(checkNumber(10)); console.log(checkStringOddEven("hello")); this 노드에서 this를 사용할 때 주의점이 존재한다. 최상위 Scope의 this는 module.exports를 가르킨다. 그 외에는 브라우저의 자바스크립트와 동일하다. 함수 선언문 내부의 this는 global(전역) 객체를 가리킨다. 노드에서의 this는 브라우저..
-
NodeJS - const, let /템플릿 문자열, 객체 리터럴/ 화살표 함수개발언어/Node.js 2023. 2. 18. 09:13
var와 const의 Scope if(true){ var x = 3; } console.log(x); //3 if(true){ const y = 3; } console.log(y); //Uncaught ReferenceError : y is not,define var는 블록 scope를 무시하다. 그래서 위 코드에서 처럼 var로 선언한 x의 경우 if 블록 밖에서도 x에 접근할 수 있다. 반면 const로 선언한 y 같은 경우는 블록 scope를 존중하기 때문에 블록 밖에서는 const y 변수에 접근할 수 없다. var가 Scope를 가지는 경우 if(true){ const x = 3; } console.log(x); //에러 function a(){ var y = 3; } console.log(y)..
-
NodeJS - Call Stack, Back Ground, Task Queue개발언어/Node.js 2023. 2. 17. 13:38
function oneMore() { console.log("one more"); } function run() { console.log("run run"); setTimeout(() => { console.log("wow"); }, 0); new Promise((resolve) => { resolve("hi"); }).then(console.log); oneMore(); } setTimeout(runs, 5000); file을 시작하면 일단 호출스택에 무조건 anonymous가 깔린다. 그리고 위 코드 대로라면 메모리에 실행되기 위한 함수 2개가 선언된다. 그리고 메서드 setTimeout이 바로 실행된다. setTimeout메서드 실행이 완료되면 호출스택에서 setTimeout(run,5000)이 ..
-
NodeJs 호출 스택,이벤트 루프개발언어/Node.js 2022. 12. 13. 10:03
1. 호출 스택 ⭐️호출 스택은 Execution Context(실행 컨텍스트)와 밀접한 연관이 있다. function first(){ second(); cosole.log('첫 번째'); } function second(){ third(); cosole.log('두 번째'); } function third(){ cosole.log('세 번째'); } first(); 함수를 선언했다는 것은 해당 함수를 메모리에 올렸다는 것이다. 메모리는 임시 저장장치이다. 컴퓨터가 잠깐 기억하고 있다가 새로 고침하면 저장이 사라진다. 마지막에 first();로 first()함수를 호출하고, 메모리속에 해당 함수가 선언이 되었는지 찾아본다. 호출하는 것은 실제로 실행하는 것이다. first()함수는 첫 줄에서 바로 sec..
-
NodeJs 블로킹과 논블로킹 I/O개발언어/Node.js 2022. 12. 12. 18:29
논블로킹이라서 순서대로 실행되지 않는다고 해도 그 순서가 램덤이 되는 것이 아니라 나름 대로의 규칙을 가진다. (프로그램 실행 순서에 랜덤은 존재하지 않는다.)-> 순서대로 실행되지 않는 것의 규칙을 Event Loop라고 한다. 논 블로킹 오래 걸리는 함수를 백그라운드로 보내서 다음 코드가 먼저 실행되고, 나중에 오래걸리는 함수를 실행 논 블로킹 방식하에서 일부 코드는 백그라운드에서 병렬로 실행된다. 일부 코드: I/O작업(파일 시스템 접근, 네트워크 요청),압축, 암호화 등 나머지 코드는 블로킹 방식으로 실행된다. I/O작업이 많으 때 노드 활용성이 극대화 된다. 블로킹 블로킹(동기)코드가 순서대로 실행되는 것은 -> Execution Context(실행 컨텍스트) 실행 컨텍스트 안에 this와 sc..
-
NodeJs 서버로서의 노드개발언어/Node.js 2022. 12. 12. 18:14
대부분의 서비스가 서버 - 클라이언트 이중 구조로 되어 있다. 서버 네트워크를 통해 클라이언트에 정보 혹은 서비스를 제공하는 컴퓨터 또는 프로그램 클라이언트 서버에 요청을 보내는 주체 (브라우저,데스크탑 프로그램,모바일 앱, 다른 서버에 요청을 보내는 서버) ⭐️노드는 서버가 아니지만, 서버를 구성할 수 있게 하는 모듈이다. 노드 서버의 장단점 장점 단점 멀티 스레드 방식에 비애 컴퓨터 자원을 적게 사용함. 싱글 스레드서 CPU 코어를 하나만 사용함. I/O 작업이 많은 서버로 적합 CPU (주방장,점원)작업이 많은 서버로는 부적합 ex)이미지 리사이징,암호화,알고리즘 문제 풀이 멀티 스레드 방식보다 쉬움 하나뿐인 스레드가 멈추지 않도록 관리해야 한다. 웹 서버가 내장되어있다. 서버 규모가 커졌을 때 서..