Express importing app from server.js is giving me an error

Viewed 662

I have created an express server in my server.js file, and I export app from it.

//server.js    

require("dotenv").config();
const express = require("express");
const app = express();

const connectToDb = require("./connectToDb")




connectToDb().catch(console.dir)


app.use((req, res) => {
  res.status(404).send("unable to find");
});

module.exports = app

I import app from server.js in the connectToDb.js file

//connectToDb.js


const app = require("./server")
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
const port = process.env.PORT || 3000;

const connectToDb = async () =>{
  try {
    await client.connect();

    console.log("Connected correctly to server");
    app.listen(port, () => {
        console.log(`Listening on port ${port}`);
    })
  } catch (err) {
    console.log(err.stack);
  } finally {
    await client.close();
    console.log("hello")
  }
}


module.exports = connectToDb

It connects succesfully to the database, but when it reaches app.listen it gives me this error: TypeError: app.listen is not a function. I don't know why it gives me an error because I have exported app. What am I doing wrong?

1 Answers

That's because you have a cyclic dependency. The two files import each other, and inside server.js you make a call immediately on load. In the moment you call connectToDb inside of server.js, the server.js file has not fully executed yet and hence the module export has not yet happened. Either way it's something you should try to avoid (cyclic dependencies).

Just resolve the cycle by passing the app to the connectToDb function as a parameter instead of importing it:

//server.js    

require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb(app).catch(console.dir)

app.use((req, res) => {
  res.status(404).send("unable to find");
});

module.exports = app


// connectToDb.js

const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
const port = process.env.PORT || 3000;

const connectToDb = async (app) =>{
  try {
    await client.connect();

    console.log("Connected correctly to server");
    app.listen(port, () => {
        console.log(`Listening on port ${port}`);
    })
  } catch (err) {
    console.log(err.stack);
  } finally {
    await client.close();
    console.log("hello")
  }
}


module.exports = connectToDb
Related