最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Read file with fs.readFileSync and eval contents...which scope have the functions? How to access? - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Oct 16, 2012 at 14:45 JohnnycubeJohnnycube 1,0601 gold badge10 silver badges25 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论