node.js: including files

The old way…

By Udo G at Stack Overflow

from: http://stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files

If, despite all the other answers, you still want to traditionally include a file in a node.js source file, you can use this:

<code>var fs = require('fs'); // file is included here: eval(fs.readFileSync('tools.js')+'');</code>
  • The empty string concatenation +'' is necessary to get the file content as a string and not an object (you can also use .toString() if you prefer).
  • The eval() can’t be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can’t create a include() utility function or something like that).

Please note that in most cases this is bad practice and you should instead write a module. However, there are rare situations, where pollution of your local context/namespace is what you really want.

share|improve this answer
answered Apr 27 ’11 at 20:13
Udo G
1,275319
4
Cool, this is useful for quick’n’dirty putting JS libs designed for client-side into a node.js app without the need of maintaining a Node-styled fork. – Kos Dec 11 ’11 at 13:24
1
The “+”” is just a shortcut to force string casting. The more readable solution would be “String(fs.readFileSync(‘tools.js’))” or if the read.FileSync returns an object then “fs.readFileSync(‘tools.js’).toString()” should also work since toString is attached to the base Object prototype (i.e Object.prototype.toString). – Evan Plaice Jan 20 at 23:22
-1 Blindly importing JS into the global namespace can open the code to unintended naming conflicts. If the code in the tools.js file were written in object literal format you could assign them to a local variable which works like a pseudo-namespace. Also, I don’t really think the eval is required (masylum’s code makes it seem like the code is already eval’d during the require). I think you’re import/eval-ing the code with require, casting that code back to string and eval-ing it again just to pidgeonhole it into the global namespace. Looks like you’re doing it wrong. – Evan Plaice Jan 20 at 23:31
1
I just answered the original question, which is about including code, not writing modules. The former can have advantages in certain situations. Also, your assumption about require is wrong: The code is certainly eval’d, but it remains in it’s own namespace and has no way to “pollute” the namespace of the calling context, hence you need to eval() it yourself. In most cases using the method described in my anwer is bad practice but it’s not me that should decide if it is for TIMEX. – Udo G Jan 21 at 17:03
1
@EvanPlaice: do you have a better suggestion which actually answers the question? If you need to include a file which is not a module, do you have a better approach than this? Otherwise, downvoting it seems absurd. – jalf Apr 21 at 11:04