-1

I am working on an expressJS project. I have a route file named send_email.js, and I want to use parts of this file from two different places. These places are index.js and user.js. So I added the following line for both of index.js and users.js:

const send_email = require("./send_mail");

But user.js is giving me an error because send_email is undefined. And then I just delete the same line from index.js and everything goes fine. I can reach send_mail in user.js, and it is what I expect.

Am I overlooking something about requiring files in expressJS? I can use this technique effectively in other projects. Are there expressJS specific things which cause this error?

I created same situation in another tiny project and its' codes like these:


// ------------------------index.js -----------------------

const express = require("express");
const app = express();

/* if coment this two line every thing goes fine */
const mylog = require("./deneme1").mylog;
mylog();
/* if coment this two line every thing goes fine */


const yourlog = require("./deneme2").yourlog;
const route = require("./deneme1").route;
console.log('route :', route);


yourlog();

app.get("/", (req, res)=>{
  res.send("OK!");
})


app.listen(3000, () => { "listening on "+3000});

// --------------deneme1.js -------------------------

const express = require("express");
const route = express.Router();
const yourlog = require("./deneme2").yourlog;
console.log('yourlog mmm:', yourlog);

route.get("/deneme", function(req, res){
  mylog();
  res.send("OK!");
});

function mylog () {
  console.log("mylog in deneme1.js");
};

module.exports.route = route;
module.exports.mylog = mylog;

// ------------------deneme2.js-----------------

const express = require("express");
const route = express.Router();

const mylog = require("./deneme1").mylog;
console.log('mylogxx :', mylog);

function yourlog(){
  console.log("yourlog deneme2");
  mylog();
  console.log("----");
}

module.exports.yourlog = yourlog;

deneme1.js and deneme2.js require each other and express.js require both of deneme1.js and deneme2.js.

2 Answers2

0

Did you export in your send_mail.js file? You should export whatever function you want to reuse . And use import wherever you need it. Instead of require. For reference :MDN

Pelumi
  • 413
  • 2
  • 5
  • 13
0

I have realized that my problem is related "cyclic dependencies" between my route files. It is kind of design mistake. And there is a stackoverflow question/solution about it: how-to-deal-with-cyclic-dependencies-in-node-js