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

标签 node.js module

我想要实现的是创建一个包含多个功能的模块。

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?

最佳答案

你可以这样做:

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');

关于node.js - 在 Node.js 中声明多个 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631064/

相关文章:

ruby - 允许对不同模块中的 Ruby 常量进行非限定访问

android - 尝试将新模块添加到项目中。无法读取脚本

python - python的pp模块上的PicklingError

mysql - 无法从 Node.js 连接到 MySql 服务器

asp.net - Azure 构建中的 Node.js 错误

node.js - 如何在本地主机中运行多个express/Nodejs应用程序?

php - 在没有重定向的情况下打开 PHP 页面?

perl - .bashrc 命令脚本中的 Term::ReadKey

node.js - 是否可以从 node.js 作为命令行参数运行 PhantomJS

javascript - 如何使 '@' 符号解析为 src