导出时函数返回未定义

时间:2020-10-16 14:15:49

标签: javascript events eventemitter module-export

我在node.js中创建了一个模块,该模块具有2个功能-takeInput和getEventEmitter。它们都已导出。但是,当我需要其他文件时,takeInput可以正常工作,但getEventEmitter却是未定义的。

以下是代码:-

// main module.js
function takeInput(db) {
    // logic to take input from user
}

function getEventEmitter(db) {
    const eventEmitter = new EventEmitter();

    console.log(takeInput);
    eventEmitter.on('function execution complete', () => takeInput(db));

    eventEmitter.emit('function execution complete');
}

module.exports = {
    takeInput,
    getEventEmitter
}

导出主module.js的模块

const { getEventEmitter } = require('main module');

// Some lines of code ...
getEventEmitter(db); // Error here when this function is called.

错误如下

TypeError: getEventEmitter is not a function

请帮助。

1 个答案:

答案 0 :(得分:0)

您将需要从main module.js导出这两个函数

function takeInput(db) {
    // logic to take input from user
}

function getEventEmitter(db) {
    const eventEmitter = new EventEmitter();
    console.log(takeInput);
    eventEmitter.on('function execution complete', () => takeInput(db));
    eventEmitter.emit('function execution complete');
}

export  { takeInput, getEventEmitter }

然后它将起作用。