Let's say we have a file called app.js. Pretty simple:
What if we have a functions inside "tools.js". How would we import them to use in apps.js?
Or...am we supposed to turn "tools" into a module, and then require it? seems hard, we rather do the basic import of the tools.js file.
We can require any js file, we just need to declare what we want to expose.
And in our app file:
If, despite all the other answers, we still want to traditionally include a file in a node.js source file, we can use this:
The empty string concatenation +'' is necessary to get the file content as a string and not an object (we can also use .toString() if we 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. we can't create a include() utility function or something like that).
Please note that in most cases this is bad practice and we should instead write a module. However, there are rare situations, where pollution of our local context/namespace is what we really want.
Please also note this won't work with "use strict"; because functions and variables defined in the "imported" file can't be accessed by the code that does the import. Strict mode enforces some rules defined by newer versions of the language standard. This may be another reason to avoid the solution described here.
We need no new functions nor new modules. We simply need to execute the module you're calling if we don't want to use namespace.
or in any other .js like myController.js :
var tools = require('tools.js') which force us to use a namespace and call tools like tools.sum(1,2); we can simply call
in my case we have a file with controllers ctrls.js
and we can use Categories in every context as public class after require('ctrls.js')()
Here is a plain and simple explanation:
We was also looking for a NodeJS 'include' function and we checked the solution proposed by Udo G - His code doesn't work with my included JS files. Finally we solved the problem like that:
Wikitechy Rated 5 / 5 based on 378284 reviews.
World's No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.