Define and using Modules: node module export or import
The module in the node is a simple JavaScript library where we write some variable and functions. in this tutorial, I am going to discuss that how we can define the module and import the module in another module. All application logic encapsulated into modules. A module is a simple javascript file which may be imported into another js file. In this example, we will create a simple module named “mymodule” and import into another js file.
Example:
Step1: Create a new node project folder and package.json using npm init command.
npm init
Above command will ask some names and creates package.json file.
Step 2: Create a new module and add the following code into it.
exports.fname = "Yogesh"; exports.lname = "sharma"; exports.fullname = function(){ return this.fname +" "+this.lname; }
In the above code, we have written a public method and public variables which are accessible in another JS file or main file “index.js” due to exports keyword.
Step 3 : Create new file index.js and add the following code into that
var http = require('http'); var obj = require('./mymodule'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write(obj.fullname()); res.end('Hello World\n'); }).listen(9000, '127.0.0.1'); console.log('Server running at http://127.0.0.1:9000/');
in this code, we have used require function to import the custom module into the current file. Using require we have created an object of the custom module.
Step 4: Run program and see output
node index.js