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; 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.
Leave a Reply