10

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.

Johnnycube
  • 1,060
  • 1
  • 10
  • 25

1 Answers1

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Thank you very much for your comment. You're right with using the wrapper function. As I'm not able to modify the files i used var examples = eval('(function() {' +fs.readFileSync('public/templates/simple.js') + 'return examples;})();');! Then at least i don't have to worry about poluting my local namespace or overriding stuff which should improve security. Also only the "known" part is returned. I somehow found the answer to the scope problem by node itself...since every module is wrapped in an anonymous scope i really cant access any function from inside the file with global["examples"]... – Johnnycube Oct 16 '12 at 15:20
  • 2
    So the basic problem is node.js Module scope not showing these damn functions...how can I access them by name? Again thanks for clarification – Johnnycube Oct 16 '12 at 15:33
  • Same answer as before: You must put them into your local scope. If you need to make `foo.bar` visible as `bar`, then you can simply say `var bar = foo.bar;`. `eval()` can see `bar`. – Aaron Digulla Oct 16 '12 at 15:44