on
노드 기능
노드 기능
module, exports
파일 끝에 module.exports로 모듈로 만들 값을 지정
다른 파일에서 require(파일 경로)로 그 모듈의 내용 가져올 수 있음
module.exports 외에도 exports로 모듈을 만들 수 있음
동일하게 동작함
동일한 이유는 module.exports와 exports가 참조 관계이기 때문
exports에 객체의 속성이 아닌 다른 값을 대입하면 참조 관계가 깨짐
// var.js const odd = '홀수입니다'; const even = '짝수입니다'; // module.exports = { odd, even }; exports.odd = odd exports.even = even
// func.js const {odd, even} = require('./var'); function checkOddorEven(number){ if (number % 2 ){ return odd; }else{ return even } } // console.log(checkOddorEven(10)) module.exports = checkOddorEven;
// index.js const { odd, even} = require('./var'); const checkNumber = require('./func'); function checkStringOddOrEven(str){ if (str.length % 2){ return odd; }else{ return even; } } console.log(checkNumber(10)) console.log(checkStringOddOrEven('Hello'));
일반적으로 export를 할 때 객체가 하나이면 module.exports = 변수(함수)
두 개 이상일땐 exports.odd = odd; exports.even = even 이런식 (module.exports ={ odd, even }; 을 사용해도 됨)
require
require가 제일 위에 올 필요는 없음
require.cache에 한 번 require한 모듈에 대한 캐슁 정보가 들어있음.
require.main은 노드 실행 시 첫 모듈을 가리킴.
하드 디스크(컴퓨터)상에 있는 파일을 실행하면 무겁고 느리니 메모리 상으로 저장시켜줘서(cache) 사용
순환 참조
각 두개의 파일이 서로 require할 때 발생 (node에서 자동으로 막아주지만 되도록이면 피해가는게 낫다)
Process
: 현재 실행중인 노드 프로세스에 대한 정보를 담고 있음
- nextTick
이벤트 루프가 다른 콜백 함수들보다 nextTick의 콜백 함수를 우선적으로 처리함
너무 남용하면 다른 콜백 함수들 실행이 늦어짐
비슷한 경우로 promise가 있음(nextTick처럼 우선순위가 높음)
아래 예제에서 setImmediate, setTimeout보다 promise와 nextTick이 먼저 실행됨
Process.nextTick(콜백)
https://www.inflearn.com/course/%EB%85%B8%EB%93%9C-%EA%B5%90%EA%B3%BC%EC%84%9C/dashboard/
본글의 모든 내용은 위 강의를 토대로 작성됩니다
from http://jhg3410.tistory.com/19 by ccl(A) rewrite - 2021-10-15 22:26:57