读取具有fs.readFileSync和eval内容的文件...哪个范围具有功能?怎么进入? [英] Read file with fs.readFileSync and eval contents...which scope have the functions? How to access?

查看:187
本文介绍了读取具有fs.readFileSync和eval内容的文件...哪个范围具有功能?怎么进入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近尝试将文件导入到现有的node.js项目中.我知道这应该使用模块来编写,但是我包括这样的外部javascript文件:

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:

 eval(fs.readFileSync('public/templates/simple.js')+'')

simple.js的内容如下:

The contents of simple.js looks like this:

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.

一切都在node.js 0.8服务器上运行,就像我说的那样...我只是不知道为什么吗?

Everything is running in a node.js 0.8 server and like I said its working...I just dont quite know why?

感谢您的澄清.

推荐答案

eval()将变量放入您调用它的地方的本地范围.

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.

我建议将文件内容更改为:

I suggest to change the content of the files to:

(function() {
    ...
    return examples;
})();

这样,您可以说:

var result = eval(file);

很明显,一切都在哪里/结束了.

and it will be obvious where everything is/ends up.

注意:eval()是巨大的安全风险;确保您仅从受信任的来源阅读.

Note: eval() is a huge security risk; make sure you read only from trusted sources.

这篇关于读取具有fs.readFileSync和eval内容的文件...哪个范围具有功能?怎么进入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆