javascript 使用 fs.readFileSync 和 eval 内容读取文件......哪个范围具有功能?如何访问?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12917348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read file with fs.readFileSync and eval contents...which scope have the functions? How to access?
提问by Johnnycube
I recently tried to import a file into my existing node.js project. I know this should be written with a module but i include my external javascript file like this:
我最近尝试将一个文件导入到我现有的 node.js 项目中。我知道这应该用模块编写,但我包含了我的外部 javascript 文件,如下所示:
eval(fs.readFileSync('public/templates/simple.js')+'')
The contents of simple.js looks like this:
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();
};
(Yes, google closure templates).
(是的,谷歌关闭模板)。
I can now call the template file using:
我现在可以使用以下方法调用模板文件:
examples.simple.helloWorld();
Everything is working like expected. However I'm not able to figure out what the scope of these functions is and where I could possibly access the examples object.
一切都按预期工作。但是,我无法弄清楚这些函数的范围是什么以及我可以在哪里访问示例对象。
Everything is running in a node.js 0.8 server and like I said its working...I just dont quite know why?
一切都在 node.js 0.8 服务器上运行,就像我说的那样工作......我只是不知道为什么?
Thanks for clarification.
感谢您的澄清。
回答by Aaron Digulla
eval()
puts variables into the local scope of the place where you called it.
eval()
将变量放入您调用它的地方的本地范围内。
It's as if the eval()
was replaced by the code in the string argument.
就好像eval()
被字符串参数中的代码替换了一样。
I suggest to change the content of the files to:
我建议将文件的内容更改为:
(function() {
...
return examples;
})();
That way, you can say:
这样,你可以说:
var result = eval(file);
and it will be obvious where everything is/ends up.
一切都在哪里/结束将是显而易见的。
Note: eval()
is a huge security risk; make sure you read only from trusted sources.
注意:eval()
是巨大的安全隐患;确保您只从受信任的来源阅读。