Introduction
In one of our projects, We had to implement plugin architecture using node js. We were targeting the following features.
1. Each plugin should have its own REST endpoint.
2. Add/delete/update of plugins shouldn't require any code change in the core framework.
3. Plugin modifications should work without manual server restart.
4. Plugins should be able to deliver its own static resources.
ImplementaTION
Our node.js server is running on express framework. We created a folder named "plugins" where the plugins can reside. Each plugin must be in its own directory and should have index.js file inside it. Directory name is the plugin name which in turn also used as the rest api prefix.
The following code snippets show sample router and plugin code (name should be myplugin/index.js but github doesn't allow / in file names, so i kept it myplugin-index.js). plugins can be accessed using /<plugin-name>/ url pattern. For example in this case endpoints in myplugin.js can be accessed using /myplugin/home and /myplugins/user/tom.
The following code snippets show sample router and plugin code (name should be myplugin/index.js but github doesn't allow / in file names, so i kept it myplugin-index.js). plugins can be accessed using /<plugin-name>/ url pattern. For example in this case endpoints in myplugin.js can be accessed using /myplugin/home and /myplugins/user/tom.
STatic resource serving
To serve static resources for a plugin, we can use router.use api of express framework. In our case, we should write router.use(express.static(__dirname + '/public')) if we have the static resources inside public directory of plugin.