Created
December 23, 2010 07:40
-
-
Save KOBA789/752707 to your computer and use it in GitHub Desktop.
外部ファイルを動的ロードするサンプル
This file contains 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 characters
/* | |
* 外部ファイルを動的ロードするサンプル | |
* | |
* node.js だとコードを修正するたびにプロセス殺して、もう一度立ちあげなきゃならないから面倒だよね。 | |
* 実行中書き換えとかできないの? ってなわけで作ってみた。 | |
* PHP とか Perl って CGI だから実行の度にプロセスが走るわけで、 | |
* コード修正したら F5 するだけで結果がわかるから超手軽なんだけど、 | |
* それだとプロセス起動のコストが高いわけで、これはその辺のジレンマも解消してみた。 | |
* | |
* コード見ればわかるんだけど外部ファイルが書き換えられた瞬間にスクリプトがコンパイルされる感じ。 | |
* 正しくはコンパイルじゃないんだけど概ねそんな感じ。 | |
* コンパイル的な作業はファイルの更新時しか走らないから効率的、なはず。 | |
* でもエラー処理とかちゃんとやってないから修正後のファイルに文法ミスとかあると全部コケるよ。 | |
*/ | |
var fs = require('fs'), | |
vm = require('vm'); | |
function loadObject (file, callback) { | |
var load = function () { | |
var sandbox = {}; | |
fs.readFile(file, function (err, data) { | |
var script = vm.createScript(data, file); | |
script.runInNewContext(sandbox); | |
obj = sandbox.exports; | |
callback(sandbox.exports); | |
}); | |
} | |
load(); | |
fs.watchFile(file, load); | |
} | |
var func; | |
loadObject('module.js', function (obj) { | |
func = obj; | |
console.log(func()); | |
}); |
This file contains 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 characters
exports = function () { | |
return 2 + 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment