Search code examples
javascriptnode.jsnode-modulesserver-side

Use functions fron another file, without require


Context:

I have 3 files, parent.js, child1.js, and child2.js

parent.js

let child1 = require("./child1.js")
let child2 = require("./child2.js")
let key = "*****"

child1.start(key)
child2.start();

child1.js

let key = false;

module.exports = {
    action: async() => {
        return someApi.get(key);
    },
    start: async(_key) => {
        key = key;
    }
}

child2.js

module.exports = {
    action: async() => {
        let res = await child1.action()
        ...
    },
    start: async() => {
        // startup actions
    }
}

The Problem

I need to run a function from child1 inside child2, but I can't use require because there can only be 1 instance of child1

Does anyone know the solution for this? Thanks


Solution

  • I think that you are asking the wrong question :)
    If you need child1 to be unique you should use a singletone and require it wherever you need it.

    //child1
    let instance
    
    module.export = () => {
      if(!instance) {
         instance = {
        action: async() => {
            return someApi.get(key);
        },
        start: async(_key) => {
            key = key;
        }
       }
       return instance
    }
    

    I personally don't love singletone approach but it can be handy

    Another approach you can try is to inject child1 service instance into child2 'constructor'
    you just have to export a function instead of an object
    parent.js

    let child1 = require("./child1.js")()
    let child2 = require("./child2.js")(child1)
    let key = "*****"
    
    child1.start(key)
    child2.start();
    

    child2

    module.exports = (child1) => {
        
        const action =  async() => {
            let res = await child1.action()
            ...
        }
        const start =  async() => {
            // startup actions
        }
        return {action, start}
    }