Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modularize code in node js

I am new to Node. I have done a sample application where I have done all the code in one file server.js

var express = require('express'),
                nconf=require('nconf');
            var app = express()
            nconf.env().file({ file: 'db-config.json'});
            app.use(express.static(__dirname+"\\client"));
            var dbConfig = nconf.get();
            console.log();
            var mysql      = require('mysql');
            var connection = mysql.createConnection({
                        host: dbConfig.hostname,
                        port: dbConfig.port,
                        user: dbConfig.user,
                        password: dbConfig.password,
                        database: dbConfig.db
            });

            app.get('/', function (req, res) {
                 res.sendFile(__dirname+"\\client\\index.html");
            })
            app.get('/getTables', function (req, res) {
                     var sql="SELECT table_name as text from information_schema.tables where table_schema = ?";
                     connection.query(sql,[dbConfig.db],function(err,rows,fields){
                     if(!err){
                      var data={

                           "children":[]
                      };
                      for(var i=0;i<rows.length;i++){
                        rows[i].leaf=true;
                        data.children.push(rows[i]);
                      }
                       res.json(data);
                     }else{
                     console.log("db not connected");
                     }

                     });

            })
            var server = app.listen(3000, function () {

              var host = server.address().address
              var port = server.address().port

              console.log('Example app listening at http://%s:%s', host, port)

            })

I want to know how to write all my mysql config code in one file and use where ever i want. And I want to write client response creation in another fie.

like image 910
Surya Prakash Tumma Avatar asked Feb 11 '26 03:02

Surya Prakash Tumma


2 Answers

As I remember there are two ways how you can exports methods or objects from other modules:

  1. module.exports
    using:

//yourModule.js

function method1(){    
}

to export this function we can do the following:

module.exports = method1;

in this case when you will use var myModule = require("./yourModule") - the myModule will be method1, i.e. to call it you will simply call myModule().

or you can exports like:

module.exports = { 
    method1: method1,
    method2: ...
}

in this case when you will use require like in case above to call functions you will need to type: myModule.method1();

  1. the 2nd way is to use directly:

exports.method1 = function (){}; exports.method2 = function (){}; exports.someObject = {};

and this will be the same as:

module.exports = { 
        method1: method1,
        method2: ...
    }

Reference

P.S. since you're using express js I recommend you to type in console: npm install express-generator -g this will create for you template project with initial structure. All folder like routes, views, javascripts and etc.

like image 66
Nicolai Avatar answered Feb 13 '26 12:02

Nicolai


Use require:

var someModule= require('./myModule');

Edit:

Read about node.js modules here: http://nodejs.org/api/modules.html#modules_modules

like image 28
Steve H. Avatar answered Feb 13 '26 11:02

Steve H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!