NodeReact020
NodeReact020

Reputation: 506

Node, Express - Index file not calling files correctly

Hi in my express project, I have my index file where I require different files to startup my application. These require a database connection file, a file for logging stuff using winston and a file for configuring routes.

I use the require() statement within express to call these files, and when I run the application(using nodemon), I expect some messages to be logged to the terminal verifying that the files have been called, however no messages occur.

Here is my code: index.js:

const express = require('express')
const app = express()

require('./startup/logging') ()
require('./startup/db') ()
require('./startup/routes') (app)

const port = process.env.PORT || 3000
app.listen(port, () => winston.info(`Listening on port: ${port}`))

db.js:

const mongoose = require('mongoose')
const winston = require('winston')

module.exports = function() {

    mongoose.connect('mongodb://localhost/dwg', {useNewUrlParser: true, useUnifiedTopology: true})
        .then(() => winston.info('Connected to MongoDB...'))
        .catch(err => console.error("Error"))
}

logging.js:

const winston = require('winston');

    module.exports = function() {
      winston.handleExceptions(
        new winston.transports.File({ filename: 'uncaughtExceptions.log' }));

      process.on('unhandledRejection', (ex) => {
        throw ex;
      });

      winston.add(winston.transports.File, { filename: 'logfile.log' });
    }

routes.js:

const express = require('express');

module.exports = function(app) {
    app.use(express.json())
}

No database is created when running the application. I can confirm this by looking at mongodb compass. The message that is meant to be printed by app.listen() is also not printed to the console. Does anybody know the issue? Thank you.

Upvotes: 0

Views: 98

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

The problem doing it this way is your app starts before it gets a chance to do rest of work like creating db connection etc. You should start the app only when these tasks are done. something like this

const express = require('express')
const app = express()

const logging = require('./startup/logging');
const db = require('./startup/db');
const routes = require('./startup/routes');

const port = process.env.PORT || 3000
app.listen(port, async () => {
  await logging();
  await db();
  await routes();
  // assuming you have winston here.
  winston.info(`Listening on port: ${port}`)
})

Mongo part is defintely async so need await. Check if routes and logging needs await or not.

Upvotes: 1

Related Questions