不同模块调用同一个模块的JS对象的函数

问题描述 投票:0回答:1

我有一个这样的架构

  • index.js -> server.js
    
  • index.js -> bot.js
    

我在index.js 中有express 服务器和bot 对象。 在index.js中有一个脚本以一定的间隔从不同的api访问数据。 当前端获取 API 的服务器端点时,我想调用 index.js 的函数来调用机器人实例的函数。是否有 npm 包或一些技巧来抛出事件并在外部模块中捕获它?

我有在 Electron.js 中使用进程间通信进行类似操作的经验,但想知道如果没有 Electron 我该如何做到这一点。另外,我不能再次从模块创建导出的对象,因为这会导致轮询错误。

一些代码可以帮助理解我的意思:

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;


服务器.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;
javascript node.js npm node-modules nodejs-server
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.