Read the file with the file fs.readFileSync and eval ... in what area are the functions? How to get access?

I recently tried to import a file into my existing node.js. project I know this should be written using a module, but I include my external javascript file as follows:

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

The content 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 closing patterns).

Now I can call the template file using:

 examples.simple.helloWorld(); 

Everything works as expected. However, I cannot understand what the scope of these functions is and where I could access the examples object.

Everything works on the node.js 0.8 server and, as I said, it works ... I just don’t know why?

Thanks for the clarification.

+6
source share
1 answer

eval() places the variables in the local area of ​​the place where you named it.

As if eval() was replaced by code in a string argument.

I suggest changing the contents of the files to:

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

So you can say:

 var result = eval(file); 

and it will be obvious where it all / ends.

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

+9
source

Source: https://habr.com/ru/post/927856/


All Articles