Read file with fs.readFileSync and eval contents…which scope have the functions? How to access?

[亡魂溺海] 提交于 2019-12-06 23:41:38

问题


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')+'')

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.

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

Thanks for clarification.


回答1:


eval() puts variables into the local scope of the place where you called it.

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;
})();

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.



来源:https://stackoverflow.com/questions/12917348/read-file-with-fs-readfilesync-and-eval-contents-which-scope-have-the-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!