Require in nodejs instance a new class

2

I need to call a method of a class which should not be instantiated again, since it causes an error.

In main.js:

var telegram = require('./telegram.js');
telegram.hello();

In telegram.js

const bot = new TelegramBot(token, {polling: true});

function hello(req) {
        console.log("hello!!");
}

module.exports.hello = hello;

The error is to instantiate the telegram bot twice:

Conflict: terminated by other long poll or webhook
    
asked by Pablo Cegarra 05.08.2017 в 10:37
source

2 answers

0

The easiest way I see is to create a global variable to cache your TelegramBot in your telegram.js

let bot = null;
if (global.cachedModule) {
    bot = global.cachedModule;
} else {
    bot = new TelegramBot(token, {polling: true});
    global.cachedModule = bot;
}

function hello(req) {
        console.log("hello!!");
}

module.exports.hello = hello;
    
answered by 07.08.2017 в 20:38
0

Let's see, what you set as an example

const bot = new TelegramBot(token, {polling: true});

function hello(req) {
        console.log("hello!!");
}

module.exports.hello = hello;

It exports you the hello function and yet, bot is not being used.

If you want to create an instance of TelegramBot, add methods to it and export that instance, then:

const bot = new TelegramBot(token, {polling: true});

bot.algo = function(){}

module.exports = bot;

You have to export to the object, not the object's method.

    
answered by 18.08.2017 в 22:57