我创建的应用程序处理一些基本操作,如保存(例如在文件系统中保存文件)编辑等,现在我希望有些用户能够使用新操作扩展此功能,例如用户 将克隆应用程序并使用新操作(和一些回调)添加其他文件,然后在某个事件上注册
我应该把这个新动作引入幕后,我的问题是如何从新文件中获取这些新动作然后在我的过程中运行,简单的例子将非常有帮助
更新 假设这是我的文件来处理操作,用户想要添加其他操作,如删除
var fs = require('fs');
module.exports = {
fileAction: function (req, res, filePath) {
var urlAction = urlPath.substr(urlPath.lastIndexOf("/") + 1);
if (urlAction === 'save') {
this.save(req,res,filePath);
} else
this.delete(req,res,filePath);
},
save: function (req,res,filePath) {
var writeStream = fs.createWriteStream(filePath, {flags: 'w'});
req.pipe(writeStream);
res.writeHead(200, { 'Content-Type': 'text/plain' });
},
delete: function (req,res,filePath) {
},
}
,删除代码应该是这样的
filePath = 'C://test.txt';
fs.unlinkSync(filePath);
现在lordvlad
建议用户应该有一个新文件及其具体实现,应由lordvlad
建议设计流程使用,我的问题是如何添加此删除功能(这非常简单)并且使其工作,就像一些 POC 一样。
答案 0 :(得分:2)
我可以想象一些像这样的插件系统:
main.js
// some setup
var EE = require('events').EventEmitter;
var glob = require('glob');
var eventBus = new EE();
// find plugins
glob("plugins/*.js", function(err, files) {
if (err) {
// some error handling here
}
files.forEach(function(file) {
var plugin = require(file);
plugin(eventBus);
});
});
插件/ MY-plugin.js
module.exports = function(eventBus) {
// do something interesting
// listen for events on the event bus
eventBus.on("foo", function(e){
// do something
});
eventEmitter.emit("pluginReady", "my-plugin");
};
当然,你可以用一些全局对象替换事件发射器,或者通过传递回调而不是事件总线来使插件处理回调。我认为关键的方面是加载插件(在glob ... require
块内完成)并使它们适合您的系统(您需要自己弄清楚或提供一些已有的代码示例,以便有人使用可以给你另一个提示)。
更新
main.js
var glob = require('glob');
var xtend = require('xtend');
module.exports = {
save: function(..){..},
load: function(..){..},
}
// typeof module.exports.delete === 'undefined',
// so you cannot call module.exports delete or similar
glob("plugins/*.js", function(err, files) {
files.forEach(function(file){
var plugin = require(file);
// call plugin initializer if available
if (typeof plugin.init === "function")
plugin.init();
xtend(module.exports, plugin);
});
// here all plugins are loaded and can be used
// i.e. you can do the following
module.exports.delete(...);
});
插件/我的-plugin.js
module.exports = {
delete: function(..){..},
init: function() {
// do something when the plugin loads
}
}
请注意,任何插件都可以覆盖其他插件的方法。