Joh*_*ube 8 javascript eval fs node.js google-closure-templates
我最近尝试将文件导入到现有的node.js项目中.我知道这应该用模块编写,但我包括我的外部javascript文件,如下所示:
eval(fs.readFileSync('public/templates/simple.js')+'')
Run Code Online (Sandbox Code Playgroud)
simple.js的内容如下所示:
if (typeof examples == 'undefined') { var examples = {}; }
if (typeof examples.simple == 'undefined') { examples.simple = {}; }
examples.simple.helloWorld = function(opt_data, opt_sb) {
var output = opt_sb || new soy.StringBuilder();
output.append('Hello world!');
return opt_sb ? '' : output.toString();
};
Run Code Online (Sandbox Code Playgroud)
(是的,谷歌关闭模板).
我现在可以使用以下方法调用模板文件:
examples.simple.helloWorld();
Run Code Online (Sandbox Code Playgroud)
一切都像预期的那样工作.但是,我无法弄清楚这些函数的范围是什么以及我可以访问示例对象的位置.
一切都在node.js 0.8服务器上运行,就像我说它的工作......我只是不知道为什么?
谢谢你的澄清.
Aar*_*lla 13
eval()
将变量放入您调用它的地方的本地范围.
就好像它eval()
被字符串参数中的代码替换了一样.
我建议将文件内容更改为:
(function() {
...
return examples;
})();
Run Code Online (Sandbox Code Playgroud)
那样,你可以说:
var result = eval(file);
Run Code Online (Sandbox Code Playgroud)
一切都在/结束的地方显而易见.
注意:eval()
存在巨大的安全风险; 确保您只从可信来源阅读.
归档时间: |
|
查看次数: |
9367 次 |
最近记录: |