javascript tutorial - [Solved-5 Solutions] In Node.js, how do we “include” functions from my other files ? - javascript - java script - javascript array



Problem:

Let's say we have a file called app.js. Pretty simple:

var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
  res.render('index', {locals: {
    title: 'NowJS + Express Example'
  }});
});

app.listen(8080);
click below button to copy the code. By JavaScript tutorial team
  • 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.

Solution 1:

We can require any js file, we just need to declare what we want to expose.

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

var zemba = function () {
}
click below button to copy the code. By JavaScript tutorial team

And in our 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
click below button to copy the code. By JavaScript tutorial team

Solution 2:

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

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
click below button to copy the code. By JavaScript tutorial team
  • 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.
  • Update 2015-08-06
  • 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.

Solution 3:

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.

in tools.js

module.exports = function() { 
    this.sum = function(a,b) { return a+b };
    this.multiply = function(a,b) { return a*b };
    //etc
}
click below button to copy the code. By JavaScript tutorial team

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')();
click below button to copy the code. By JavaScript tutorial team

and then

sum(1,2);
click below button to copy the code. By JavaScript tutorial team

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

module.exports = function() {
    this.Categories = require('categories.js');
}
click below button to copy the code. By JavaScript tutorial team

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

Solution 4:

Here is a plain and simple explanation:

Server.js content:

// Include the public functions from 'helpers.js'
var helpers = require('./helpers');

// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';

// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);
click below button to copy the code. By JavaScript tutorial team

Helpers.js content:

// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports = 
{
  // This is the function which will be called in the main file, which is server.js
  // The parameters 'name' and 'surname' will be provided inside the function
  // when the function is called in the main file.
  // Example: concatenameNames('John,'Doe');
  concatenateNames: function (name, surname) 
  {
     var wholeName = name + " " + surname;

     return wholeName;
  },

  sampleFunctionTwo: function () 
  {

  }
};

// Private variables and functions which will not be accessible outside this file
var privateFunction = function () 
{
};
click below button to copy the code. By JavaScript tutorial team

Solution 5:

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:

var fs = require("fs");

function read(f) {
  return fs.readFileSync(f).toString();
}
function include(f) {
  eval.apply(global, [read(f)]);
}

include('somefile_with_some_declarations.js');

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - In Node.js, how do we “include” functions from my other files ?