Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement plugin-in architecture with JavaScript/Node.js

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.

like image 887
Ryan Avatar asked Aug 10 '12 05:08

Ryan


People also ask

What is plugin in node JS?

Request Fusebit Demo. Writing a plugin system enables your application to be extensible, modular, and customizable. This is a guiding principle for the most popular Node. js web frameworks, as we already covered in our previous blog post Plugin Architecture Overview Between Express, Fastify and NestJS.

Can you use node js with JavaScript?

When using Node. js, you may exchange code between client and server apps, and you can use JavaScript for the entire development process, allowing for improved communication between back-end and front-end teams.

What is plugin architecture?

A plug-in is a bundle that adds functionality to an application, called the host application, through some well-defined architecture for extensibility. This allows third-party developers to add functionality to an application without having access to the source code.

How do JavaScript plugins work?

Introduction. Plugins in JavaScript allow us to extend the language to achieve some powerful (or not so powerful) features we desire. Plugins/libraries are essentially packaged code that save us from writing the same thing (features) over and over again. Just plug it in, and play!


2 Answers

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.

like image 159
BadCanyon Avatar answered Sep 24 '22 07:09

BadCanyon


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
like image 22
juandopazo Avatar answered Sep 22 '22 07:09

juandopazo