简体   繁体   English

如何在NodeJS中动态加载外部配置文件

[英]How to load external configuration files in NodeJS dynamically

In a NodeJS application I would like to load configuration data (reports to be generated) from external files dynamically. 在NodeJS应用程序中,我想从外部文件动态加载配置数据(要生成的报告)。 I can load them statically by using require('path/config'); 我可以使用require('path / config')静态地加载它们;

But I do have parts of the configuration that need to be refreshed on a regular schedule and, to make it all more complicated, these configuration files contain a function that must be executable. 但是,我确实有一部分配置需要定期刷新,并且要使其变得更加复杂,这些配置文件包含必须可执行的功能。

One such report looks as follows: 其中一份报告如下所示:

const report = {
  name : 'Report 3',
  description : 'Very simple report.',
  // Some properties
  preprocessor : function() {
  },
  // Some more properties
};

module.exports = report;

When using require to re-load the report it is basically not reloaded. 使用require重新加载报告时,基本上不会重新加载报告。 Even if I change something, it stays the same. 即使我更改了某些内容,它也保持不变。 (Reason: require() uses caching and rightfully it does.) (原因:require()使用缓存,并且确实使用缓存。)

What is a good way (maybe an external library) to re-load external configuration files that contain executable functions? 重新加载包含可执行功能的外部配置文件的好方法(也许是外部库)是什么?

I would use fs . 我会用fs If you have complete control over the configuration files (otherwise it's dangerous) you can use eval . 如果您完全控制配置文件(否则很危险),则可以使用eval

var fs = require('fs');

var file = fs.readFileSync(filename);
var module = {}
eval(file);

// You can access report in module.exports

If you don't want to block your application (usually recommended) you should use the async version and provide callbacks. 如果您不想阻止您的应用程序(通常建议),则应使用异步版本并提供回调。

To circument caching problems, I now use the library require-without-cache . 为了解决缓存问题,我现在使用库require-without-cache Seems to do the job. 似乎做好了工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM