Home » Node.js

Export Import of files in Node JS

In this article, we will learn about the importing and exporting of source code files in Node JS.
Submitted by Mansha Lamba, on October 18, 2018

This is a great asset of Node JS, which enables programmers to use a code file’s content in another code file. Also, it is just a matter of one or two commands that support reusability of code to a great extent.

For elaborating I have 4 code files:

Code file 1:

// this essentially will first run the whole code 
//of b then do the module export wala thing
var detail=require('./b');  

console.log(detail.info);

detail.info=5;

console.log(detail.info);

detail.print();

detail.printagain();

Code file 2:

var z=1;

function hey(){
	console.log("hello ");
}

hey();

// module.exports.info=z;
// better way of doing this neeche hai !!!!
// module.exports.print=hey;

// 2nd method
module.exports={
	info:z ,
	print:hey ,
	printagain: function(){
		console.log("how r u ? ");
	},
	
	// object factory ,, each file importing this file 
	//can get individual copy of number
	object: function(){ 
		return {
			number:0
		}
	}
}


// this command cant run becoz printagain is 
// defined inside module.exports,, u can say this
// printagain();         
// is the disadvantage  2nd method

Code file 3:

var coding=require('./b');

console.log(coding.info);

var object=coding.object();
console.log(object.number);

object.number=10;
console.log(object.number);

Code file 4:

require('./a');

require('./c');

Output for code file 1

Output 1

Output for code file 2

Output 2

Output for code file 3

Output 3

Output for code file 4

Output 4

These code files are very comprehensive and easy to understand and all the fundamental concepts are covered in them. DON’T IGNORE COMMENTS IN CODE FILES. Major concepts are covered in it.

Essentially it is important to note that for exporting variables and functions of a code file we need to use the module. Exports at the end of that code file and for importing a code file in another code file we need to use require followed by path for code file that is to be imported.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.