-
[Node.js] node.js 모듈 사용하기programming/node.js 2020. 3. 30. 21:45반응형
node.js 노드js에서 모듈을 사용하기 위한 정리
app.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersconst a_module = require("./a-module"); const b_module = require("./b-module"); console.log(a_module.callFn1()); console.log(a_module.callFn2("param")); b_module.fn3(); b_module.fn4("test msg"); a-module.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersconst testFn1 = function(){ return "a-module : testFn1"; } const testFn2 = function(msg){ return "a-module : testFn2 : " + msg; } module.exports.callFn1 = testFn1; module.exports.callFn2 = testFn2; b-module.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersconst fn3 = function(){ console.log("b-module : call fn3"); } const fn4 = function(msg){ console.log("b-module : msg : " + msg); } module.exports = { fn3, fn4 } app.js에서 a-module.js와, b-module.js를 require해서 불러온다.
이때 .js는 붙이지 않아도 된다.(붙여도 작동하긴 한다.)
각 모듈에서 module.export를 이용하면 모듈을 밖에서 불러서 사용할 수 있다.
이때 a-module.js 처럼
module.exports.callFn1 = testFn1;
사용할 수 있다.
그리고 b-module.js처럼 여러개를 한번에 exports할 수 도 있다.
반응형'programming > node.js' 카테고리의 다른 글
[nodejs] github 커밋 카운터 프로그램 3 (0) 2019.12.02 [nodejs] github 커밋 카운터 프로그램 2 (0) 2019.12.01 [nodejs] moment.js로 지난 일주일 날짜 구하기 (0) 2019.11.30 [nodejs] github 커밋 카운터 프로그램 (0) 2019.11.27 [node.js] process 객체 더보기 (0) 2019.11.25