6

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

But the problem is my server.js and don't know how many plugins I need to init and load, and they can start in particular order.
I suppose that the PluginManager.register method collects the init functions in an array. Then PluginManager.loadPlugins might call with some async helper library (eg async) all of theese init functions, and after call the app.listen callback - something like this: async.parallel(initFunctions, callback)
In terms of the loading, you could have used promises, and let everything "settle" before continuing. ES6 Promises
1

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

2 Comments

Yes, for init hook I can block, but in the future I might have other runtime hook such as on_result_ready, on_get etc, are there any recommendation for a plugin pattern for JS?
You can look at how YUI implements plugins yuilibrary.com/yui/docs/plugin. Objects that can have plugins augment PluginHost which has plug and unplug methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.