[英]Accessing function from exported module (node.js)
I have been reading up on this and apprently there are more ways to export a module in node.js. 我一直在阅读有关内容,显然,有更多的方法可以在node.js中导出模块。
One of the simple things you can do with modules is to encapsulate functions within a file like so: 您可以对模块执行的简单操作之一就是将函数封装在文件中,如下所示:
module.exports = {
sayHelloInEnglish: function() {
return "HELLO";
},
sayHelloInSpanish: function() {
return "Hola";
}
};
However i would like to create some more dirverse modules and so ive created the following user module: 但是我想创建更多的dirverse模块,因此我创建了以下用户模块:
var UserModule = function (socket) {
var userList = [];
socket.on('userData', function (userDetails) {
userDetails.socket = socket;
userList[userDetails.id] = userDetails
});
socket.on('getActiveUsers', function () {
socket.emit('activeUsers', userList);
});
function helloWorld (){
console.log('hello world');
}
};
module.exports = function (socket) {
return new UserModule(socket);
};
now i am requireing this module in my io instance: 现在我在io实例中需要此模块:
io.on('connection', function (socket) {
var my_user = userList.id;
socket.on('userData', function (userDetails) {
userDetails.socket = socket;
userList[userDetails.id] = userDetails
});
var userModule = require('./costum_modules/UserModule.js')(socket);
userModule.helloWorld();
var chatModule = require('./costum_modules/ChatModule.js')(socket, userModule);
var cacheModule = require('./costum_modules/CacheModule.js')(socket, userModule);
var notificationModule = require('./costum_modules/NotificationModule')(socket, sequelize, userList);
});
The socket.on
methods are working fine in my UserModule
however i am unable to call the function helloWorld
. socket.on
方法在我的UserModule
中运行良好,但是我无法调用函数helloWorld
。 if i try i get the following error: 如果我尝试以下错误:
userModule.helloWorld is not a function
So my question is, is what i am trying to do even possible? 所以我的问题是,我要做什么甚至可能? how am i able to store
objects
, functions
ect in a module for later use? 我如何在模块中存储
objects
, functions
以备后用?
function helloWorld
is essentially a private function for use within your userModule. function helloWorld
本质上是在userModule中使用的私有函数。
You can make it public by changing the function declaration to the following: 您可以通过将函数声明更改为以下内容来使其公开:
this.helloWorld = function (){
console.log('hello world');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.