I have a architecture like this
-
index.js -> server.js -
index.js -> bot.js
I have in index.js both express server and bot objects. In index.js there are a script that access data from different api with some interval. When frontend fetch server's endpoint of an API i want to call function of an index.js to call a function of a bot instance. Is there a npm package or some trick to throw event and catch it in outer module?
I have experience of doing like that in electron.js with Inter-Process Communication but wonder how i can do it without electron. Also I can't just create exported object from module again because it will cause polling error.
Some code to help understand what i mean:
index.js
// Bot
const bot = require("./bot");
// Admin-panel
const adminPanel = require("./server");
async function start() {
// Simplified main script
const data = await axios.get("Some link here")
if (data.someData == true){
bot.sendMessage(someId,`Some message`)
}
}
bot.js
const TelegramBot = require("node-telegram-bot-api");
const bot = new TelegramBot(process.env.BOT_TOKEN, { polling: true });
bot.on("message", (msg) => {
// Some action
}
);
bot.on("polling_error", console.log);
module.exports = bot;
server.js
const express = require("express");
const path = require("path");
const app = express();
const fs = require("fs");
app.use(express.json());
app.use(express.static(path.resolve(__dirname, "..", "public")));
app.use("/api/sendMessage", (req, res) => {
const {message} = req.body;
// Call bot.sendMessage(someId, message) from here
});
app.listen(5000);
module.exports = app;
For those who wondering, this may be your answer https://stackoverflow.com/a/51958272/23296640
https://nodejs.org/en/learn/asynchronous-work/the-nodejs-event-emitter