Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在node.js中为module.exports的所有方法导入模块_Javascript_Node.js_Module_Node Modules - Fatal编程技术网

Javascript 在node.js中为module.exports的所有方法导入模块

Javascript 在node.js中为module.exports的所有方法导入模块,javascript,node.js,module,node-modules,Javascript,Node.js,Module,Node Modules,我有一个node.js模块,我想导出它,它包含多个函数。其中许多功能都需要一个通用模块,如下代码所示: module.exports = { a: function () { const util = require("commonModule"); // Do things }, b: function () { const util = require("commonModule"); // Do o

我有一个node.js模块,我想导出它,它包含多个函数。其中许多功能都需要一个通用模块,如下代码所示:

module.exports = {

    a: function () {
        const util = require("commonModule");
        // Do things
    },

    b: function () {
        const util = require("commonModule");
        // Do other things
    },

    c: function () {
        const util = require("commonModule");
        // Do more other things
    }
}
如果module.exports格式中没有此功能,我只需执行以下操作并导入模块一次,所有功能都可以使用此功能:

const util = require("commonModule");

function a(){
// Do things using commonModule
}

function b(){
// Do other things using commonModule
}

是否有办法修改module.exports版本,以便用户在导入我的模块时自动导入commonModule并为所有函数提供它,而不是让每个函数调用导入commonModule的新实例?

您不需要在每个单独的函数中都需要它。您可以简单地执行以下操作:

const util = require("commonModule");
module.exports = {

    a: function () {
        // Do things
    },

    b: function () {
        // Do other things
    },

    c: function () {
        // Do more other things
    }
}
或者,如果您愿意,请执行以下操作:

const util = require("commonModule");

function a(){
// Do things using commonModule
}

function b(){
// Do other things using commonModule
}

module.exports.a = a;
module.exports.b = b;
甚至第三种方式:

const util = require("commonModule");

module.exports.a = function (){
// Do things using commonModule
}

module.exports.b = function () {
// Do other things using commonModule
}


你选择哪一个取决于你。

如果我的回答帮助你确保接受它,这样其他人就会知道你的问题已经解决。我知道,只是问题出来10分钟后我才能接受,所以一旦问题解决了,我就接受它。你太快了;D