我是node.js的新手并尝试创建我的第一个模块。 但我收到了一个错误
TypeError: Object function SetAstAppLog.....has no method 'on'
我的模块文件包含以下代码:
var EventEmitter = require('events').EventEmitter;
var util = require('util');
module.exports = SetAstAppLog;
util.inherits(SetAstAppLog, EventEmitter);
function SetAstAppLog(logFolderPath,fileNamePrefix,fileSize,logStreamObject) {
EventEmitter.call(this);
.
.
.
.
this.emit('objCreated');
}
在app.js中我正在做以下事情:
var SetAstAppLog = require('astAppLog');
var fileSize = 1024;
SetAstAppLog.on('objCreated', function () {
console.log('an object was created');
});
SetAstAppLog.on('written', function () {
console.log('Write operation completed.');
});
var objCommLogger = new SetAstAppLog(logFolderPath,logCommFilePrefix,fileSize,logCommMsg);
var objErrorLogger = new SetAstAppLog(logFolderPath,logErrorFilePrefix,fileSize,logErrorMsg);
这里,我使用节点js和v0.10.21。
即使我的模块文件包含EventEmitter
,我也无法找出为什么我收到此错误
任何人都可以帮忙解决这个问题吗?
答案 0 :(得分:3)
您正在导出该函数而不调用它。你需要打电话给它:
var SetAstAppLog = require('astAppLog')();
编辑:我没注意到您在脚本中调用了较低的函数。您应该将事件处理程序附加到实例,而不是构造函数。
var objCommLogger = new SetAstAppLog(logFolderPath, logCommFilePrefix, fileSize, logCommMsg);
objCommLogger.on(...);