1

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?

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

just edit my answer .did you use it the same as me? if not please post your new code
Its exactly the same as shown at the post but with the modifications you've suggested :/
ok so please console log app and con inside index.js and upload the output
Finally got it working, for some reason the Express library routing was creating conflict, i've used another file for testing it and now it's working, marking as accepted
0

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.

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.