In Node.js, how do I "include" functions from my other files? In Node.js, how do I "include" functions from my other files? javascript javascript

In Node.js, how do I "include" functions from my other files?


You can require any js file, you just need to declare what you want to expose.

// tools.js// ========module.exports = {  foo: function () {    // whatever  },  bar: function () {    // whatever  }};var zemba = function () {}

And in your app file:

// app.js// ======var tools = require('./tools');console.log(typeof tools.foo); // => 'function'console.log(typeof tools.bar); // => 'function'console.log(typeof tools.zemba); // => undefined


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

var fs = require('fs');// file is included here:eval(fs.readFileSync('tools.js')+'');
  • 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.

Update 2015-08-06

Please also note this won't work with "use strict"; (when you are in "strict mode") 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.


You need no new functions nor new modules.You simply need to execute the module you're calling if you don't want to use namespace.

in tools.js

module.exports = function() {     this.sum = function(a,b) { return a+b };    this.multiply = function(a,b) { return a*b };    //etc}

in app.js

or in any other .js like myController.js :

instead of

var tools = require('tools.js') which force us to use a namespace and call tools like tools.sum(1,2);

we can simply call

require('tools.js')();

and then

sum(1,2);

in my case I have a file with controllers ctrls.js

module.exports = function() {    this.Categories = require('categories.js');}

and I can use Categories in every context as public class after require('ctrls.js')()