node.js - Nodejs 导出函数

标签 node.js

我正在使用 module.exports 导出模块列表。下面是我的 模型/Message.js

var msgModel = function()
{
    var getMsg = function() {
        return "Hello World";
    }
    return{
        getMsg : getMsg
    }
}
module.exports =  msgModel;

下面是我的app.js

var msgModel = require('./Models/Message');
console.log(msgModel.getMsg());

它引发了我的错误

console.log(msgModel.getMsg());
                 ^

我无法找出问题所在。

最佳答案

您需要执行console.log(msgModel().getMsg());。这是因为 msgModel 是一个函数。我建议像下面的示例一样重写您的 msgModel 以实现您想要的调用。

var msgModel = {
    getMsg: function() {
        return "Hello World";
    }
};

module.exports = msgModel;

关于node.js - Nodejs 导出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42771250/

相关文章:

node.js - 在 Git post-receive hook 中运行无限长的进程

javascript - 等到处理完成后再导出 Node.js 模块?

node.js - 如何确定何时将功能引入 React

node.js - exec 与 execFile nodeJs

javascript - 如果 json 对象具有字符串、 bool 值和数字类型的组合,如何迭代它

javascript - Node PostgreSQL 超时客户端的查询

node.js - 通过父子连接连接到多个数据库时的 MongoDB 性能

javascript - Node 和 MySQL - 解决 "Too Many Connections"问题

javascript - 如何从 JS 或 Node.js 发布?

node.js - 使用 Firebase 电子邮件/密码身份验证的 CSRF 保护