最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Implement plugin-in architecture with JavaScriptNode.js - Stack Overflow

programmeradmin3浏览0评论

Below is a simple node.js using express

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello World');
});

app.listen(3000);

I want to implement a plugin-in architecture, such as by default there is a folder called plugins, and they register by themselve when the node.js startup, I don't need to modify the main server.js

an example a foo plugin, e.g.

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

Then in my server.js, I would have something like

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

My problem is my plugin codes are all asynchronous , there is no way to block before the app.listen(), do you have any idea for a better plugin-in architecture implementation?

Thanks.

Below is a simple node.js using express

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello World');
});

app.listen(3000);

I want to implement a plugin-in architecture, such as by default there is a folder called plugins, and they register by themselve when the node.js startup, I don't need to modify the main server.js

an example a foo plugin, e.g.

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

Then in my server.js, I would have something like

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

My problem is my plugin codes are all asynchronous , there is no way to block before the app.listen(), do you have any idea for a better plugin-in architecture implementation?

Thanks.

Share Improve this question asked Aug 10, 2012 at 5:04 RyanRyan 10.2k28 gold badges99 silver badges164 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Seems like whatever is loading the plugins would raise a callback like anything else.

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

This way the app wouldn't start listening until the plugins are all loaded.

You should block. It will only impact the "start time" of the application, not the "run time".

  • Use fs.readdirSync to get all files in the plugins directory
  • Write them as modules and require() them all (require is synchronous)
  • Plug them into your Server
发布评论

评论列表(0)

  1. 暂无评论