1

So here is how my code looks like :

const mod = require("./module.js")
let functionA = () => {
    return new Promise((resolve, reject) => {
         databasequery("sql", (response) => {
             databasequery("sql", (response) => {
                 console.log(mod)
             });
         });
    });
}

When I call this functionA, the console.log() prints {}, like if mod was an empty object. But when I move the mod definition into the scope of the function like this :

let functionA = () => {
    const mod = require("./module.js")
    return new Promise((resolve, reject) => {
         databasequery("sql", (response) => {
             databasequery("sql", (response) => {
                 console.log(mod)
             });
         });
    });
}

Suddenly, my console.log outputs me the expected object, with the functions I exported in my module.

Can anyone explain why changing the scope of the module suddenly makes everything work / break ?

Note : I don't set / create a mod variable ANYWHERE else in the code.

Note 2 : obviously, those aren't the real names of the function and module nor the real content, and my query functions look different too, but I tried to keep the hierarchy of callbacks and promises the same.

Note 3 : this is a cyclic / recursive require, but I don't see why would that be a problem.

Edit 1 : A few functions are exported from the required module. In my module source, the export looks like this :

module.exports = {
    "createInstance": createInstance,
    "getCurrentWebsocket": getCurrentWebsocket
};

Edit 2 : I reported a bug for nodejs https://github.com/nodejs/node/issues

Edit 3 : module.js code :pastebin.com/QxmxDfhm

16
  • Can you show what is exported from module.js ? and how ? Commented May 14, 2020 at 21:02
  • I edited my question Commented May 14, 2020 at 21:06
  • What do you get by printing mod directly in the module where functionA is defined ? (In your first example) Commented May 14, 2020 at 21:09
  • by adding a console.log(mod) right after it prints me an empty object. I very confused because putting a require in a different scope shouldn't change the contents of that require... Commented May 14, 2020 at 21:11
  • Also, I can't do the edit because it's less than 6 characters, but I guess the "equals" characters were not intended just after the second databasequery call. Commented May 14, 2020 at 21:11

1 Answer 1

2

I got you a great explanation why this is happening. there is also a solution offer end of the article. Hope it helps. article

Sign up to request clarification or add additional context in comments.

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.