node.js, using external js files

Node js exports example, assume it’s written in a file includes1.js

exports.greeting = function(){
	    console.log("Hey, how are you!");
	}

exports.printDate = function(){
		console.log(Date());	    
	}

exports.pi = 3.14;

exports.a = [0,1,2,3,4,5,6,7,8,9];

Node js module.exports example, it does the same as the above code but written in module.exports. Assume it’s written in includes2.js

module.exports = {
	greeting: function()
	{
	    console.log("Hey, how are you!");
	},

	printDate: function()
	{
		console.log(Date());	    
	},

	pi: 3.14,
	
	a:[0,1,2,3,4,5,6,7,8,9]
}

To include external js file, for example, one of the above js file, it uses the require function which will return an object with all the functions or variables that are delcared with exports. This object then saved to a variable. In this case, it saves the external file as an object in the variable myincludes.

var myincludes = require('./includes1.js'); //or includes2.js, works the same but differnt style.
var pi=myincludes.pi;
var a=myincludes.a;

myincludes.greeting(); //Hey, how are you!
myincludes.printDate();//Sun Nov 09 2014 20:56:55 GMT-0500 (EST)
console.log(pi); //3.14
console.log(a);  //[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search