简体   繁体   English

导出时返回 undefined 的函数

[英]Function returning undefined when exported

I created a module in node.js that has 2 functions - takeInput and getEventEmitter.我在 node.js 中创建了一个模块,它有 2 个函数 - takeInput 和 getEventEmitter。 Both of them are exported.这两个都是出口的。 But when I require it is some other file, takeInput works fine but getEventEmitter turns out to be undefined.但是当我需要它是其他一些文件时,takeInput 工作正常但 getEventEmitter 结果未定义。

Here are the codes:-以下是代码:-

// 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 where main module.js is exported导出 main module.js 的模块

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

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

The error is as follows错误如下

TypeError: getEventEmitter is not a function

Please help.请帮忙。

You will need to export those 2 functions from main module.js您需要从 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 }

Then it will work.然后它会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM