일반 사용자 모듈 만들기

황제낙엽 2019.07.09 04:12 조회 수 : 41735

sitelink1 https://opentutorials.org/module/938/7190 
sitelink2  
sitelink3  
sitelink4  
extra_vars4  
extra_vars5  
extra_vars6  

exports 객체와 모듈의 기본

exports : 사용자 모듈 만들기(여러 속성과 메소드), require()

http://www.nodejs.org/api/globals.html#globals_exports

http://www.nodejs.org/api/modules.html#modules_modules

만들고자 하는 모듈을 파일로 만들고 exports 객체의 속성이나 메소드를 정의해주면 모듈을 만들어 낼 수 있습니다. 그리고 만들어진 모듈을 전역 함수 require()를 이용하여 추출합니다. 

두 번째 링크에 나오는 예제를 그대로 따라해 보겠습니다. circle.js가 모듈이 되는 파일이고 foo.js가 실행될 파일입니다.

예제

1
2
3
4
5
6
7
8
9
10
// cicle.js
var PI = Math.PI;
 
exports.area = function (r) {
return PI * r * r;
};
 
exports.circumference = function (r) {
return 2 * PI * r;
};
1
2
3
4
// foo.js
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
+ circle.area(4));

실행 결과

1
2
$ node foo.js
The area of a circle of radius 4 is 50.26548245743669

어려운 코드가 아니므로 이해할 수 있을 것입니다. 다만 node의 문법적인 부분을 살펴봅시다.

circle.js에서 area와 circumference를 exports 객체의 메소드로 정의했습니다. 그리고 foo.js에서 require() 함수를 통해 circle.js 파일을 불러와 결과 값을 변수 circle에 대입했습니다. 그럼 이제 foo.js에서 변수 circle을 통해 circle.js의 exports 객체에 추가한 속성이나 메소드를 사용할 수 있게 됩니다.

 

module.exports : 사용자 모듈 만들기(하나의 속성이나 메소드)

http://www.nodejs.org/api/globals.html#globals_module

위 예제에서는 전역 객체 exports를 이용했지만 이번에는 module.exports를 사용해 보겠습니다.

결론부터 말하면 exports는 속성이나 메소드를 여러 개 정의할 수 있지만 module.exports는 하나만 정의할 수 있습니다. 파일 자체를 속성이나 메소드로 사용하는 방식입니다.

예제는 링크 http://www.nodejs.org/api/modules.html#modules_modules 의 두 번째 예제입니다. square.js가 모듈이 되는 파일, bar.js가 실행될 파일입니다.

예제

1
2
3
4
5
6
7
8
// square.js
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
1
2
3
4
// bar.js
var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());

실행 결과

1
2
$ node bar.js
The area of my square is 4

square.js에서 module.exports를 함수로 정의했습니다. 그러면 bar.js에서 square.js 파일을 require()를 통해 변수로 불러와 모듈로 사용할 수 있는데 그 변수가 바로 함수로 사용됩니다.

 

함수 뿐 아니라 마찬가지로 속성도 지정할 수 있습니다.

예제

1
2
// mymodule.js
module.exports = "사용자 모듈입니다.";
1
2
3
// mymain.js
var mymodule = require('./mymodule.js');
console.log(mymodule);

실행 결과

1
2
$ node mymain.js
사용자 모듈입니다.

 

index.js 파일

1
var module = require('./mymodule');

만약 위처럼 확장자를 입력하지 않으면 어떻게 될까요?

  1. 먼저 mymodule.js 파일을 찾습니다. 있다면 그 파일을 추출합니다.
  2. mymodule.js 파일이 없다면 mymodule 이라는 폴더를 찾습니다. 그리고 그 폴더의 index.js 파일을 찾아 추출합니다.
번호 제목 글쓴이 날짜 조회 수
197 XMLHttpRequest.timeout 황제낙엽 2018.11.03 248
196 IFrames and cross-domain security file 황제낙엽 2012.01.13 246
195 UTF-8 한글 초성 추출 (자바스크립트) 황제낙엽 2019.05.07 243
194 Why does this simple Javascript prototype not work in IE? 황제낙엽 2011.03.24 242
193 Function.apply and Function.call in JavaScript 황제낙엽 2011.10.07 238
192 브라우저에서 뒤로 가기 막기와 펑션키(function key) 막기 황제낙엽 2005.10.21 236
191 두 서버의 자원을 접근하는 클라이언트 프레임웍(Next.js)에서의 CORS오류 file 황제낙엽 2021.12.05 231
190 JavaScript Closures for Dummies 황제낙엽 2009.04.08 227
189 Javascript ArrayBuffer ? Binary handling in javascript 황제낙엽 2012.03.19 218
188 javascript array contains method 황제낙엽 2011.08.19 210
187 char to hex string 황제낙엽 2011.11.29 206
186 How to use Rhino to script Java classes. 황제낙엽 2008.07.14 198
185 Page Refresh/Reload 황제낙엽 2007.08.24 197
184 [펌] 아사페릴의 사생활 - Code Conventions for the JavaScript Programming Language 황제낙엽 2009.04.02 194
183 Reference Count (순환참조) 황제낙엽 2011.11.24 191
182 JavaScript Form Validation file 황제낙엽 2008.11.24 186
181 code compressor & decompressor 황제낙엽 2015.01.02 181
180 자바스크립트의 데이터 타입과 변수 황제낙엽 2008.08.06 179
179 SelectBox 밑에 CheckBox가 포함된 리스트 만들기 file 황제낙엽 2007.01.16 178
178 서비스 워커 file 황제낙엽 2020.05.25 177