Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected identifier when using module.exports (Node.js)

Tags:

node.js

I have the following module that I am using to connect to my database:

module.exports = {

    var sequelize = new Sequelize('db', 'rt', 'pw', {
      host: "localhost",
      port: 3306,
      socketPath: '/var/run/mysqld/mysqld.sock',
      dialect: 'mysql'
    })
}

and then in the main file,

var configDB = require('./config/database.js');

But unfortunately this returns the following error:

/config/database.js:3
    var sequelize = new Sequelize('db', 'rt', 'pw', {
        ^^^^^^^^^
SyntaxError: Unexpected identifier
    at exports.runInThisContext (vm.js:69:16)
    at Module._compile (module.js:432:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Module.require (module.js:357:17)
    at require (module.js:373:17)
    at Object.<anonymous> (/server.js:14:16)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)

Am I using the exports functionality incorrectly? This error occurs for every object in the exports module.

EDIT: The following returns cannot call method .authenticate of undefined, even though the module seems to export without errors.

configDB.sequelize // connect to our database
  .authenticate()
  .complete(function(err) {
    if (!!err) {
      console.log('Unable to connect to the database:', err)
    } else {
      console.log('Connection has been established successfully.')
    }
  }) 
like image 717
erythraios Avatar asked Nov 10 '22 12:11

erythraios


1 Answers

You're using incorrect syntax in your object literal. I'm not sure exactly what you're trying to accomplish (specifically, how do you intend to use configDB in your main file?), but you've got some weird hybrid of object literal syntax and functional syntax going on. Perhaps you want something like the following:

var sequelize = new Sequelize('db', 'rt', 'pw', {
  host: "localhost",
  port: 3306,
  socketPath: '/var/run/mysqld/mysqld.sock',
  dialect: 'mysql'
});
module.exports = sequelize;

Edit: You're misunderstanding several fundamental things about how resources get stored and passed around in javascript, given your current structure it seems to me that you need to replace database.sequelize with configDB:

var configDB = require('./config/database.js');
configDB
  .authenticate()
  .complete(function(err) {
    if (!!err) {
      console.log('Unable to connect to the database:', err)
    } else {
      console.log('Connection has been established successfully.')
    }
  })
like image 107
Jason Avatar answered Nov 15 '22 12:11

Jason