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 ?
initfunction atsqlRequete.jsmodule and pass any objects?