I am working on a home automation project in NodeJS with several modules. These modules need access to data devices within a central DeviceManager
. Normally I would create a singleton for this purpose so all modules access the same state of the DeviceManager
.
To create a singleton I use:
class DevicesManagerInstance {
constructor() {
this.devices = {};
}
addDevice(id, device) {
this.devices.id = device;
}
}
let DevicesManagerInstance = new DevicesManager();
module.exports = DevicesManagerInstance;
I've found some older questions regarding singletons and sharing data but still not satisfied with the answer to the question if it is de NodeJS way to share data:
- https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/
- Singleton pattern in nodejs - is it needed?
- NodeJS: Sharing Application State Between Modules
But also read singletons are an anti-pattern. Can someone clarify what is the "NodeJS" way of sharing data between modules (in my case the devices). In Angular I would create a service for this purpose.