Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create a module in Node.js

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 122
    Comment on it

    How to create our own module in Node.js so that we can use the functionality of the module in our code where we need it, instead of writing the same logic. Here we will use the test.js file as a module in our index.js file. Suppose on hitting the url: http://localhost:8831/index.js we want to create an http server.


    1- Now we will create a test.js file with the following code.

    var testhttp = require("http"); 
    
    // In the below line createServer is a function in http module of Node    
    
    
    
    function execute(){
    
        function on_Request(request, response) {
    
    // In the below line writeHead is a function of response object
    
       response.writeHead(200, {"Content-Type": "text/plain"});
    
    // In the below line write is a function of response object
    
    response.write("Yes my testhttp server is working..");
    
    //end function of response object ends the response
    response.end();    
    
    }
    var server = testhttp.createServer(on_Request);
    server.listen(8831);
    }
    
    exports.obj = execute;
    

    2- Now we will create an index.js file where we have start our testhttp server. Write the below code in the index.js file

    var testhttp_obj = require(./test);
    
    testhttp_object.obj();
    

    3- Now go to the terminal and execute the following command

    user@username:~$ cd /var/www/html/project_root_directory
    
    user@username:/var/www/html/project_root_directory$ nodejs index.js
    

    4- Now open a browser and write the following url:

    http://localhost:8831/index.js
    
    output on the browser: Yes my module test.js  is working..
    output on the terminal:  testhttp server has started
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: