nodejs删除服务器文件,javascript - 运行时添加/删除/重新加载NodeJS时无需重启服务器(也没有nodemon) - 堆栈内存溢出...

我有一个工作项目,基本上是在创建一种CMS形式,随着时间的推移,我们将向其中添加应用程序。

我们面临的问题是在服务器上的运行时加载(更具体地修改)那些应用程序。

之所以需要这种形式的“热加载”,是因为我们不希望服务器在进行更改后就重新启动,更具体地说,我们希望通过管理面板添加新的应用程序。

Nodemon是用于开发的有用工具,但是对于我们的生产环境,我们希望能够替换现有应用程序(或模块/插件,如果需要的话)而无需重新启动服务器(无论是手动还是通过nodemon),服务器都需要一直运行)。

您可以将其与Drupal,Yoomla或Wordpress等CMS的处理方式进行比较,但是出于我们的需求,出于多种原因,我们认为Node是更好的选择。

在代码方面,我正在寻找类似的东西,但这将起作用:

let applications = []

//add a new application through the web interface calling the appropiate class method, within the method the following code runs:

applications.push(require('path/to/application');

//when an application gets modified:

applications.splice(index,1);

applications.push('path/to/application');

但是我还要求调整该应用程序的现有实例。

例:

// file location: ./Applications/application/index.js

class application {

greet() {

console.log("Hello");

}

}

module.exports = application;

应用加载程序将在所述应用中加载:

class appLoader {

constructor() {

this.List = new Object();

}

Add(appname) {

this.List[appname] = require(`./Applications/${appname}/index`);

}

Remove(appname) {

delete require.cache[require.resolve(`./Applications/${appname}/index`)]

delete this.List[appname];

}

Reload(appname) {

this.Remove(appname);

this.Add(appname);

}

}

运行代码:

const AppLoader = require('appLoader');

const applications = new AppLoader();

applications.add('application'); // adds the application created above

var app = new applications.List['application']();

app.greet();

// Change is made to the application file, .greet() now outputs "Hello World" instead of "Hello"

//do something to know it has to reload, either by fs.watch, or manual trigger

applications.Reload('application');

app.greet();

预期的行为是:

Hello

Hello World

实际上,我得到:

Hello

Hello

如果有人可以帮助我找出一种动态加载此类应用程序的方法,而且还可以在运行时删除/重新加载它们,将不胜感激!

编辑:如果有一种方法可以在不使用require的情况下运行我的应用程序代码,这将允许动态加载/重新加载/删除,那也是一个受欢迎的解决方案