04-15 06:09
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[WebApp / Express] 간단한 Node Module 만들기 본문

Programming/Web App

[WebApp / Express] 간단한 Node Module 만들기

cinema4dr12 2015. 10. 27. 00:07

이번 글에서는 NodeJS의 Express Framework에 대하여 간단한 Node Module을 작성하는 방법을 알아보도록 하자.

방법 1 - 각 Method를 개별적으로 Export

{EXPRESS_APP_PATH}/routes/mymod.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var name = exports.name = 'GChoi';
var secret = 'gchoi';
 
exports.lower = function(input) {
    return input.toLowerCase();
};
 
exports.upper = function(input) {
    return input.toUpperCase();
};
 
exports.get_name = function() {
    return name;
};
 
exports.get_secret = function() {
    return secret;
};


{EXPRESS_APP_PATH}/routes/test.js

1
2
3
4
5
6
7
var mymod = require('./mymod.js');
 
console.log(mymod.name);
console.log(mymod.lower("MacBook"));
console.log(mymod.upper("Apple"));
console.log(mymod.get_name());
console.log(mymod.get_secret());


{EXPRESS_APP_PATH}/routes/app.js

1
2
3
...
var test = require('./routes/test');
...

Part 2 - JSON Format으로 Export

{EXPRESS_APP_PATH}/routes/mymod2.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var secret = 'MacBook';
 
module.exports = {
    name: 'iPhone',
 
    lower: function(input) {
        return input.toLowerCase();
    },
 
    upper: function(input) {
        return input.toUpperCase();
    },
 
    get_name: function() {
        return this.name;
    },
 
    get_secret: function() {
        return secret;
    }
};


{EXPRESS_APP_PATH}/routes/test.js

1
2
3
4
5
6
7
var mymod2 = require('./mymod2.js');
 
console.log(mymod2.name);
console.log(mymod2.lower("MacBook"));
console.log(mymod2.upper("Apple"));
console.log(mymod2.get_name());
console.log(mymod2.get_secret());


{EXPRESS_APP_PATH}/routes/app.js

1
2
3
...
var test = require('./routes/test');
...


Comments