Nodeのモジュール
サーバサイドJavaScript Node.js入門 を年末に一読したのでまとめ。
module.exportsによるモジュールの定義
module.exports = {
funA: function(){ // 無名関数をfunAという名前で外部公開する
}
}
function funB(){
}
module.exports.funB = funB; // funBをfunBという名前で外部公開する
module.exports.objC = {
foo: 'bar', // objCという名前のオブジェクトを外部公開する
fun: function(){
};
helloモジュールの定義
helloモジュールの利用
# pwd
/root/projects/node/5
# ls
hello.js
# node
> var hello = require('./hello');
undefined
> hello
{ say: [Function],
getCount: [Function],
resetCount: [Function] }
> hello.say('foo');
Hello foo
undefined
> hello.say('bar');
Hello bar
undefined
> hello.say('hoge');
Hello hoge
undefined
> hello.getCount();
3
1つのNodeプロセス内でrequire()を複数実行してもモジュールファイルが実行されるのはたった1度だけ
> require('./hello');
{ say: [Function],
getCount: [Function],
resetCount: [Function] }
> require('./hello');
{ say: [Function],
getCount: [Function],
resetCount: [Function] }
> hello.getCount();
3
> var hello = require('./hello');
undefined
> hello.getCount();
3
require()によるモジュールのロード
- ../または./で始まるパスは相対パスとして解決
- /で始まるパスは絶対パスとして解決
- これら2つ以外のパスの場合は
node_modulesディレクトリを検索して解決されたファイルのパス
NODE_PATH環境変数の値を検索して解決されたファイルのパス
から順にパスの解決が行われる。
メインモジュールかを判断する
モジュールがどこから読まれたかを確認
# node
> require.resolve('./hello')
'/root/projects/node/5/hello.js'
> require.resolve('http')
'http'