alex55132
alex55132

Reputation: 177

Using variables through scripts using module.exports not working

So im pulling my hair here and everything I've tried hasn't worked. I have a simple node.js app structure, like this:

var express = require('express');
var path = require('path');

var mysql = require('mysql');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);


//Database handler
//Here is completed with the data
var con = mysql.createConnection({
  host: "",
  user: "",
  password: "",
  database: ""
});

con.connect(function (err) {
  if(err) throw err;
  console.log("connected");
});

app.listen(55132, function () {
  console.log("Server running at port 55132");
});

module.exports = app;

Quite simple, some routing but nothing weird. I need to use the variable con in my other scripts, so i've tried this:

module.exports.database = con;

So i should be able to use it in my index.js script (see var indexRouter), soooo here is the index.js script:

var express = require('express');
var router = express.Router();
let app = require('../app');

let connection = app.database;

console.log(app); //Here returns {} so I can´t access any of the properties of the module

/* GET home page. */
router.get('/', function(req, res, next) {

}

module.exports = router;

I don't know what should I do, some suggestion?

Upvotes: 1

Views: 196

Answers (2)

Anshuk
Anshuk

Reputation: 91

You can you try with

for and example :

var function = function(coid, userid, callback)   {}
exports.function = function ;

in your case

exports.database = con;

Now it should work, you won't need to add module in the above.

Upvotes: 0

Naor Tedgi
Naor Tedgi

Reputation: 5707

for forther reading i recommend you to read this https://nodejs.org/api/modules.html#modules_exports_shortcut

just change you app file export to

 module.exports = {app,con};

and in your index file

const {app,con} = require('./app');
let connection = con;

Upvotes: 1

Related Questions