[21/12/05] 노드JS - require

[21/12/05] 노드JS - require

console.log(require);

위 코드를 입력하면 나오는 정보가 있다.

[Function: require] { resolve: [Function: resolve] { paths: [Function: paths] }, main: Module { id: '.', path: 'c:\\vscodeWork\\lecture', exports: {}, parent: null, filename: 'c:\\vscodeWork\\lecture\\index.js', loaded: false, children: [], paths: [ 'c:\\vscodeWork\\lecture\

ode_modules', 'c:\\vscodeWork\

ode_modules', 'c:\

ode_modules' ] }, extensions: [Object: null prototype] { '.js': [Function (anonymous)], '.json': [Function (anonymous)], '.node': [Function (anonymous)] }, cache: [Object: null prototype] { 'c:\\vscodeWork\\lecture\\index.js': Module { id: '.', path: 'c:\\vscodeWork\\lecture', exports: {}, parent: null, filename: 'c:\\vscodeWork\\lecture\\index.js', loaded: false, children: [], paths: [Array] } } }

require.main은 노드 실행 시 첫 모듈을 가르킴

require.extenstions는 말 그대로 확장자

require.cache는 한 번 require 한 모듈 정보에 대한 cache 정보가 들어가있다.

cache를 사용하는 이유 : 파일에서 계속 등록하는 것보다 캐시에 적재 후 끌어오는게 더 빠르므로

메모리에서 가져오는 것보다 램에서 가져오는 것이 속도가 항상 빠르다.

여기서 require 로 서로를 참조했을 때 발생하는 문제

Index.js

const index2 = require('./index2'); console.log('I need index2'); module.exports = () => { console.log('index2', index2); };

Index2.js

const index = require('./index'); console.log('I need index'); module.exports = () => { console.log('index', index); }

Index-process.js

const index = require('./index'); const index2 = require('./index2'); index(); index2();

콘솔 창에서 node index-process 를 입력하면 다음과 같은 경고가 나온다.

I need index I need index2 index2 [Function (anonymous)] index {} (node:18648) Warning: Accessing non-existent property 'Symbol(nodejs.util.inspect.custom)' of module exports inside circular dependency (Use `node --trace-warnings ...` to show where the warning was created) (node:18648) Warning: Accessing non-existent property 'constructor' of module exports inside circular dependency (node:18648) Warning: Accessing non-existent property 'Symbol(Symbol.toStringTag)' of module exports inside circular dependency (node:18648) Warning: Accessing non-existent property 'Symbol(Symbol.iterator)' of module exports inside circular dependency

Warning : 모듈이 circular dependency(순환참조) 하고 있음

그리고 호출스택에 index2에는 anonymous가 있는데 반해 index는 빈객체가 되었다.

이것은 순환참조를 그냥 내버려두면 서로를 끝없이 참조하기 때문에 하나의 객체를 빈 객체로 만들어 순환참조를 방지하는 것이다.

노드 자체에 순환참조를 방지하는 기능이 있긴 하지만 순환참조 자체가 일어나지 않게 하는 것이 좋다

from http://codingfeed.tistory.com/6 by ccl(A) rewrite - 2021-12-05 17:00:31