On-demand require()

守給你的承諾、 提交于 2019-12-02 02:18:32

This may possible if you called the "MainClass" to dynamically load the additional modules on-demand. But I suspect this will also mean an adjustment in the api to access the module.

I am guess your motivation is to "avoid" the extra processing used by "non-required modules". But remember Node is single threaded so the memory footprint of loading a module is not per-connection, it's per-process. Loading a module is a one-off to get it into memory.

In other words the modules are only ever loaded when you start your server not every-time someone makes a request.

I think you looking at this from client-side programming where it's advantages to load scripts when they are required to save on both processing and or http requests.

On the server the most you will be saving is few extra bites in memory.

Looks like the only way is to use getters. In short, like this:

exports = {
    MainClass : require('main.js').MainClass,
    get a(){ return require('./a.js'); },
    get b(){ return require('./a.js'); }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!