How to access functionality from various JS files in Node.js

In this post we will take a look on working with different JS files in Node.js. To start with let us assume a scenario that you have several js files and you need to work with these js files and use functionalities from these files in server.js.

In Node a JS file is a module. So to work with one file in another you need to load the module. For example if you want to work with A.js in server.js then you need to load A.js in server.js using require.


Let us assume that we have a file or module names Product.js as below.

var product =
 productName : "Pen",
 productPrice : 200,
 productStock : false

Now let us say we need to export

  • Product price
  • Product name

Export can be done using module.exports. So productName and productPrice will be exported to other modules as productname and productprice.


Here we are not exporting productStock. Product.js can be modified with export as below,

var product =
 productName : "Pen",
 productPrice : 200,
 productStock : false

module.exports.productname = product.productName;
module.exports.productprice = product.productPrice;

As of now export is done. Next to work with Prdouct.js module in any other files(module) we need to load it. So this can be loaded in server.js using require


After loading module in product variable, you can access productname as


In Server.js productprice and productname from Product.js can be fetched as below,

var product = require('./product');
var pname = product.productname;
var pprice = product.productprice ;

In output you should get productprice and proudctname printed. If you try to access productstock you will get error since this is not exported.

I hope you find this post useful. Thanks for reading.

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

2 thoughts on “How to access functionality from various JS files in Node.js”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s