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.

image

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.

clip_image002

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

clip_image002[6]

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

clip_image004

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


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


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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s