在Node.js中声明多个module.exports

438

我想要实现的目标是创建一个包含多个函数的模块。

module.js:

module.exports = function(firstParam) { console.log("You did it"); },
module.exports = function(secondParam) { console.log("Yes you did it"); }, 
// This may contain more functions

main.js:

var foo = require('module.js')(firstParam);
var bar = require('module.js')(secondParam);

我的问题是firstParam是一个对象类型,而secondParam是一个URL字符串,但当我这样做时,它总是抱怨类型错误。

在这种情况下,我该如何声明多个module.exports


对于任何想要了解如何导出多个 require 方法或者 require 方法与其他函数组合的人,答案在这里 - Neo
21个回答

886

你可以这样做:

module.exports = {
    method: function() {},
    otherMethod: function() {},
};

或者只需要:

exports.method = function() {};
exports.otherMethod = function() {};

然后在调用脚本中:

const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');

17
我这里没有使用 module.method,只有 exports.method,它只是对 module.exports.method 的引用,所以行为方式相同。唯一的区别是我们没有定义 module.exports,因此它默认为 {},除非我错了。 - mash
@mash,如果使用以下代码在另一个文件中能行吗:var otherMethod = require('module.js')(otherMethod);?也就是说,这行代码是否会像页面上唯一的函数并且导出为 module.exports = secondMethod; 一样需要 otherMethod 函数? - YPCrumble
4
你可以使用 var otherMethod = require('module.js').otherMethod 的语法来调用另一个模块中的方法。 - mash

234

要导出多个函数,您可以像这样列出它们:

module.exports = {
   function1,
   function2,
   function3
}

然后在另一个文件中访问它们的方法是:

var myFunctions = require("./lib/file.js")

然后您可以通过调用每个函数来调用:

myFunctions.function1
myFunctions.function2
myFunctions.function3

31
在访问它们时,你还可以这样操作:const { function1, function2, function3 } = require("./lib/file.js"),这使你能够直接调用它们(例如使用function1而不是myFunctions.function1)。 - David Yeiser

74

除了@mash的答案之外,我建议您始终执行以下操作:

const method = () => {
   // your method logic
}

const otherMethod = () => {
   // your method logic 
}

module.exports = {
    method, 
    otherMethod,
    // anotherMethod
};

请注意:

  • 您可以从otherMethod中调用method,这一点非常重要
  • 需要时,您可以快速将方法隐藏为私有方法
  • 对于大多数 IDE 来说,这更容易理解和自动完成您的代码 ;)
  • 您还可以使用相同的技术导入模块:

    const {otherMethod} = require('./myModule.js');


3
请注意,这里使用了es6对象初始化快捷方式 - https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Object_initializer - chrismarx
2
在我看来,这是更好的答案,因为它解决了从otherMethod访问方法的问题。感谢您指出这一点。 - Jeff Beagley
1
我正在寻找如何编写const {otherMethod} = require('./myModule.js');,你如何称呼这种从{}中导入方法的方法? - Franva
3
当你在赋值语句的右侧使用require(./myModule.js)时,实际上你正在将整个模块作为一个单一对象导入,然后当你在赋值语句的左侧使用const {otherMethod}时,你正在进行称为“解构赋值”的操作。你可以在MDN上阅读更多关于它的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring - Fareed Alnamrouti
但如果我的方法是异步的,我想在其他方法中调用该方法怎么办? - Lube
@Lube,你仍然可以使用普通的awaitYourPromise.then来完成这个操作,只需注意如果method是异步的,那么otherMethod也需要是异步的,这样才能调用method。如果不是异步的,你仍然可以在没有await的情况下完成它,但这将被视为反模式。 - Fareed Alnamrouti

30

模块.js:

const foo = function(<params>) { ... }
const bar = function(<params>) { ... } 

//export modules
module.exports = {
    foo,
    bar 
}

主要.js:

// import modules
var { foo, bar } = require('module');

// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);

18

这只是为了我自己的参考,因为我想要实现的目标可以通过这种方式实现。

module.js

我们可以像这样做

    module.exports = function ( firstArg, secondArg ) {

    function firstFunction ( ) { ... }

    function secondFunction ( ) { ... }

    function thirdFunction ( ) { ... }

      return { firstFunction: firstFunction, secondFunction: secondFunction,
 thirdFunction: thirdFunction };

    }

main.js 文件中

var name = require('module')(firstArg, secondArg);

12

如果文件使用ES6导出方式编写,您可以写:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};

11

你可以通过创建一个新的对象来代替替换模块的方式来实现目标。

例如:

var testone = function () {
    console.log('test one');
};
var testTwo = function () {
    console.log('test two');
};
module.exports.testOne = testOne;
module.exports.testTwo = testTwo;

并打电话

var test = require('path_to_file').testOne:
testOne();

8
你可以像我下面这样使用... 对于函数和箭头函数都适用:
greet.js:

function greetFromGreet() {
  console.log("hello from greet module...");
}

const greetVar = () => {
  console.log("greet var as a arrow fn/...");
};

module.exports = { greetVar, greetFromGreet }; // ---- multiple module export...

// -----------------------------------------------

app.js:

该文件是Node.js应用程序的主要入口点。它包含了整个应用程序的核心逻辑,其中包括引入所需的模块、设置服务器端口、处理HTTP请求和响应等。
const greetFromGreets = require("./greet");

greetFromGreets.greetFromGreet();
greetFromGreets.greetVar();

Great! What can I translate for you?

1
然后你也可以这样做。const { greetFromGreets, greetVar } = require("./greet"); greetFromGreet(); greetVar(); - undefined

7
你可以编写一个手动委派其他函数的函数:
你可以编写一个函数,手动调用其他函数。
module.exports = function(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};

这是一种实现函数重载的方法,但不太优雅。我认为Mash的答案更清晰,更好地展示了意图。 - Nepoxx

7

有多种方法可以做到这一点,下面介绍其中一种方法。 假设您有以下样式的 .js 文件:

let add = function (a, b) {
   console.log(a + b);
};

let sub = function (a, b) {
   console.log(a - b);
};

您可以使用以下代码片段导出这些函数,
 module.exports.add = add;
 module.exports.sub = sub;

您可以使用以下代码片段来调用导出的函数:

var add = require('./counter').add;
var sub = require('./counter').sub;

add(1,2);
sub(1,2);

我知道这是一份迟到的回复,但希望这能有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接