Search code examples
node.jsrequirecommonjsmodule.exports

commonJS module: exported as a function, imported as an object


I can't wrap my head around this: I have a module in my project where the module.exports is assigned a function:

//collectionWatch module:

const mongoose = require("mongoose");
const { addHistoryLog } = require("../../logsHistory");
function watchCollection(model, userInfo) {
    if (mongoose.Connection.host !== 'localhost') {
        let collectionWatcher = model.watch();
        collectionWatcher.on("change", async change => {
            await addHistoryLog(change, userInfo);
        });
    };
};

module.exports = watchCollection;

Now I import the function in several other modules, and everything works fine. Except for this one:

//some CRUD module:

//import
const watchCollection = require("../../../helpers/collectionWatch");

//function
async function updatePHRSettings(body, userInfo) {
  watchCollection(PHRS, userInfo);
  return PHRS.findOneAndUpdate({ clientID: body.clientID }, body, {
    upsert: true,
    new: true
  }).lean();
};

here, the watchCollection function throws an "not a function" error! (and when debugged, it appears to be an empty object!) what is going on with this particular require?


Solution

  • An empty object as the result of require() is usually caused by a circular reference where A requires B and B requires A or it can involve more than just two modules, but still creates a circular loop.

    The solution is usually to extract common code to a new module C so A and B can both require C, but not each other.