본문 바로가기
node.js

모듈화

by 루에 2015. 12. 3.
반응형

exports 명령어를 이용해서 모듈화 할 수 있다.


server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
var http = require("http");
 
function start(){
    http.createServer(function(request, response){
        console.log("Request received.");
        response.writeHead(200, {"Content-Type""text/plain"});
        response.write("Hello World");
        response.end();
    }).listen(8888);
 
    console.log("Server has started");    
}
 
exports.start = start;
cs


server.js의 start()를 exports.start 라는 이름으로 모듈화 했다.


그리고 다른 파일에서 호출한다.


index.js

1
2
3
var start = require("./server");
 
start.start();
cs


index.js에서 ./server를 호출해서 exports로 지정한 start를 호출한다. 이렇게 하면 파일별로 역할을 구분할 수 있다.


그러면 모듈화하지 않은 함수를 호출하면 어떻게 될까?


server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http = require("http");
 
function start(){
    http.createServer(function(request, response){
        console.log("Request received.");
        response.writeHead(200, {"Content-Type""text/plain"});
        response.write("Hello World");
        response.end();
    }).listen(8888);
 
    console.log("Server has started");    
}
 
function end(){
    console.log("call end");
}
 
exports.start = start;

cs


server.js파일에 end()를 추가하고 exports로 설정하지 않았다.

그리고 index.js에서 이를 호출한다.

1
2
3
4
var start = require("./server");
 
start.start();
start.end();
cs


어떻게 될까?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
C:\Users\Administrator\data_node>node index.js
Server has started
C:\Users\Administrator\data_node\index.js:5
start.end();
      ^
 
TypeError: start.end is not a function
    at Object.<anonymous> (C:\Users\Administrator\data_node\index.js:5:7)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:118:18)
    at node.js:952:3
 
C:\Users\Administrator\data_node>
cs


start.end is not a function 이라는 문구를 볼 수 있다. 파일을 로드할 수는 있지만, exports되지 않은 함수는 호출할 수 없다.

반응형

댓글