Surya Prakash Tumma
Surya Prakash Tumma

Reputation: 2193

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.

Upvotes: 2

Views: 8687

Answers (4)

Zeck
Zeck

Reputation: 317

You can use Environment Variables, to setup your server and database params.

Use node-env-file module, to load this settings from .env file:

dev.env

DATABASE_URL=localhost:3306 DATABASE_USERNAME=root DATABASE_PASSWORD= SERVER_IP=127.0.0.1 SERVER_PORT=3000

Usage:

app.listen(process.env.SERVER_IP || '127.0.0.1', process.env.SERVER_PORT || 3000);

https://www.npmjs.com/package/node-env-file

Upvotes: 0

Nicolai
Nicolai

Reputation: 1953

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.

Upvotes: 8

Steve H.
Steve H.

Reputation: 6947

Use require:

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

Edit:

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

Upvotes: 1

utnas
utnas

Reputation: 448

You can write an api for you DB module and require this module in your main file.

var mysql = require('mysql');

...

connect = function (dbConfig) {
    mysql.createConnection({
        host: dbConfig.hostname,
        port: dbConfig.port,
        user: dbConfig.user,
        password: dbConfig.password,
        database: dbConfig.db
    });
};

select = 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");
        }
    });
};

In your main file you can require this file.

var myDBAPI = require('./myDBAPI');

app.get('/', function (req, res) {
  res.sendFile(__dirname+"\\client\\index.html");
});

app.get('/getTables', myDBAPI.select(req, res));

PS: Don't forget ; after instructions

Upvotes: 0

Related Questions