Search code examples
javascriptnode.jsnpmmodule.exports

How to exports npm module to another file without using require function in that file


I want to know how to export the npm module to another file without using the required function on that file.

-index.js-

const cv = require("opencv4nodejs");
const add = require("./addon");

cv.imshowWait("", add.img());

my main javascript file show like this

-addon.js-

const cv = require("opencv4nodejs");

exports.img = () =>{
    return cv.imread("lenna.jpg")
}

my exports javascript file shows like this

simply in hear addon.js file read image file and exports to the index.js file and in hear it shows the image. it is working fine

But I want to remove the require function

const cv = require("opencv4nodejs");

on the addon.js file

and exports that npm module from the index.js file to the addon.js file. Something like this in the index.js file

const cv = require("opencv4nodejs");
const add = require("./addon")(cv);

How to do that guys...


Solution

  • You need to export a function which accepts the cv and makes it available in your module. So something like bellow:

    // addon.js
    
    var cv;
    
    const img = () =>{
        return cv.imread("lenna.jpg")
    }
    
    module.exports = function (opencv4nodejs) {
        cv = opencv4nodejs;
        return { img };
    }
    

    Then use it as you already shown:

    // index.js
    const cv = require("opencv4nodejs");
    const add = require("./addon")(cv);
    
    cv.imshowWait("", add.img());