/ 

Ref/singleton!

How to Code a Singleton in Node.js

URL copied to clipboard
By AstroMacGuffin dated  last updated 
![laptop-g276260f56_1280.jpg](/static/img/mm/coding/laptop-g276260f56_1280.jpg) This will be a short article because it's an easy topic. Node.js caches your modules when you `require()` them, but there's a caveat: if there's a change in the path to the file being required, it gets treated as a separate module, with a separate cache entry. As long as you code around that hiccup, you'll be slinging singletons in no time. But first, why are singletons even useful? Imagine you have a game engine. Modern games live and die on events, and your code has to register events in such a way as to ensure all the events are in the same registry. If they aren't, then your event chains won't work: event A is supposed to trigger event B, but if events A and B are registered in two separate objects, that chain of events won't happen. Of course, doing things the normal way, you'd have this at the top of your file: ```js const gameEventManager = require('./path/GameEventManager'); ``` That module naturally ends with this: ```js module.exports = new GameEventManager(); ``` ...and then whenever you need to use the `gameEventManager` you'd do this: ```js gameEventManager.registerEvent( theEvent ); ``` We'll be making some slight modifications to get a Node singleton.

🔍

Valid HTML!Valid CSS!Powered by Node.js!Powered by Express.js!Powered by MongoDB!