使用 JavaScript/Node.js 实现插件架构

Implement plugin-in architecture with JavaScript/Node.js

本文关键字:实现 插件架 js Node JavaScript 使用      更新时间:2023-09-26

下面是一个简单的节点.js使用express

var express = require('express');
var app = express();
app.get('/', function(req, res){
  res.send('Hello World');
});
app.listen(3000);

我想实现一个插件架构,比如默认有一个名为plugins的文件夹,它们在节点启动时自行注册.js不需要修改主server.js

一个foo插件的例子,例如

PluginManager.register("init, function(app) {
    app.get('/foo', function(req, res){
        res.send('Hello from foo plugin');
    });
});

那么在我的server.js,我会有类似的东西

// TODO: Scan all scripts under the folder `plugins`
// TODO: Execute all the `init` hook before the app.listen
app.listen(3000);
我的

问题是我的插件代码都是异步的,没有办法在app.listen()之前阻止,你对更好的插件架构实现有什么想法吗?

谢谢。

似乎加载插件的任何内容都会像其他任何东西一样引发回调。

PluginManager.loadPlugins(function() { app.listen(3000); });

这样,在插件全部加载之前,应用程序不会开始侦听。

你应该阻止。它只会影响应用程序的"开始时间",而不会影响"运行时间"。

  • 使用 fs.readdirSync 获取 plugins 目录中的所有文件
  • 将它们编写为模块并全部require()require同步)
  • 将它们插入您的Server