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

Problem

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.

Problem courtesy of: Johnnycube

Solution

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.

Solution courtesy of: Aaron Digulla

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.