2

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.

2
  • The require function is there for a reason Commented Feb 16, 2015 at 19:35
  • 1
    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. From there you also will see how everytying is connected, but any way you should use require like in the answer below. Commented Feb 16, 2015 at 19:48

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use require:

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

Edit:

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

1 Comment

while this is absolutely correct, some background information about about splitting the code into individual modules and then requiring them would be helpful :)
0

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

1 Comment

You should separate file with a singke responsability. Your DBAPI should be in a separeted file. In this case you case you can test it separetly.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.