来自module.js的app.js中的触发器函数



第一次发布海报——请原谅(并叫我出来(任何格式错误!

假设我有app.js,它需要module.js。在module.js中,我运行了一个express服务器,它可以接收简单的Web请求(GET/POST(。当我在module.js中收到请求时,有什么方法可以触发app.js中的功能吗?

大致如下:

var webModule = require('./module.js')
webModule.on('GET', async function (req) {
//do stuff with the request
});

我不只是把express服务器放在app.js中的原因是,我想运行一定数量的代码来验证请求是否合法,然后在单独的脚本中重用module.js,以最大限度地减少代码量,并避免每次更新身份验证过程时都要更新5-6个脚本。

您可以使用Node.js中存在的Event系统。如果设置正确,您可以在每次调用时发出一个事件,并让侦听器响应该事件。

Node.JS文档中的示例:

const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');

在您的情况下,您可以创建一个扩展EventEmitter的类,用于每个请求。然后,当请求被调用时,这个类可以发出一个事件,然后通过设置监听器在app.js文件中处理该事件。

我可能有一个解决方案,需要一些时间来编码(因为我的问题显然是非常简化(。

module.js:中

var functionActions = {};
module.exports = {
on : (async function(requestType, returnFunction){
functionActions[requestType].do = returnFunction;
});
}

//general express code
app.get('*', function(req,res) { 
if (verifyRequest(req) == 'okay'){ //authentication
return functionActions['GET'].do();
} else { //if the request is not authorised
res.status(403).send('Stop trying to hack me you stupid hacker ಠ╭╮ಠ');
}
});

一旦我发现了潜在的问题,我会尝试并更新这个答案。

最新更新