简体   繁体   中英

Function returning undefined when exported

I created a module in node.js that has 2 functions - takeInput and 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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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