0

I have trouble sharing an object between app.js and an imported file.

app.js

'use strict';

module.exports = require('./lib/express');

var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var sql = require('./lib/sqlRequete');
var app = express();

// Init database
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'master2i'
});
connection.connect();

app.post('/ajaxRequete', urlencodedParser, function(req,res){
    sql.formerSql(req.body);
});

app.listen(port,function(){
    console.log("Le serveur est lancé et écoute sur le port "+port);
});

sqlRequete.js

'use strict';

var exports = module.exports = {};

exports.formerSql=function(req){

  var SQL;

  switch(req.action){
    case 'login':
      SQL = "SELECT * FROM users WHERE pseudo ='" + req.pseudo + "' AND pass = '" + req.psw + "'";
      this.executeSql(SQL,'SELECT');
      break;
  }
}

exports.executeSql=function(requete, type){

  switch(type){

    case 'SELECT':
      connection.query(requete, function(err,rows,fields){
         if (err){
          throw err;
        }else{
          console.log('The solution is: ',rows);
        }
      });
      break;
  }
}

sqlRequete.js cannot access variable and object from app.js. As an example, I can't access connection What are the solutions ? How should I structure my code ?

2
  • What about add init function at sqlRequete.js module and pass any objects? Commented May 7, 2016 at 15:07
  • This would work in this case because connection will not change. But if I have variable or object wich there values are changing in app.js, they will be deprecated on sqlRequete.js, didn't they ? Commented May 7, 2016 at 15:21

2 Answers 2

2

You can pass objects from app.js to sqlRequete.js file by the following way.

sqlRequete.js

module.exports = function(connection){
   function formerSql(req){
     var SQL;
     switch(req.action){
        case 'login':
          SQL = "SELECT * FROM users WHERE pseudo ='" + req.pseudo + "' AND pass = '" + req.psw + "'";
          this.executeSql(SQL,'SELECT');
          break;
     }
   }

   function executeSql(requete, type){
     switch(type){
       case 'SELECT':
          connection.query(requete, function(err,rows,fields){
          if (err){
            throw err;
          }else{
            console.log('The solution is: ',rows);
          }
       });
       break;
     }
   }  
   return { 
      formerSql : formerSql,
      executeSql : executeSql
   }
}

And in app.js, pass the connection object

 var mysql      = require('mysql');
 var connection = mysql.createConnection({
   host     : 'localhost',
   user     : 'root',
   password : '',
   database : 'master2i'
 });
 connection.connect();
 var sql = require('./lib/sqlRequete')(connection);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Will the connection object be always up-to-date or saved at the time of the require call ?
Sorry about the typo. I wrote the code in this browser and mistakenly skipped the function keyword.
Yes, it should. You should try it.
I fastly tried it, and it is only copying the value at the time of the require call. Howewer, it is still a good solution for a const object I guess.
2

Usually you'll be using a third file (in your case scenario).

A resulting folder structure like this:

- index.js
- lib/
|__ orm.js
|__ app.js
|__ sqlRequete.js

Where the orm.js file is creating the connection an returning the instance:

var mysql      = require('mysql');
module.exports = function () {
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'master2i'
    });
    connection.connect();

    // IMPORTANT
    // here is where you're sharing variables between files!
    return connection;
}

However, specifically for your example, I'd simply move the initialisation of the SQL instance to the sqlRequete.js file.

exports.start = function () {
    // Init database
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'master2i'
    });
    connection.connect();
}

And request it on the app.js:

var app = express();

sql.start();

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.