/ 

Ref/nodejs!

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.

How to Sanitize Inputs for Web App Security in Node.js

URL copied to clipboard
By AstroMacGuffin dated  last updated 
![If your website is hackable, it will be hacked eventually.](/static/img/mm/villains/he-buries-the-competitionSmall.jpg) One of the friendly members of the JavaScript Mastery discord server did me a favor by performing some security auditing on this website. I admit, I was in a rush to launch, and I wasn't in any hurry to spend time on security steps. When I tried the `mongo-sanitize` NPM package it did nothing, so there went my lazy option. But I already had code for stripping symbols from a string, thanks to the search index / relevance-weighted search project. It just needed a little adjustment. Once you have something that can sanitize inputs, you need to use it. And, because every input is different, there's no getting around this part - you have to analyze your input-handling code line-by-line for ways you can be hacked. That means inputs that: - get used for database inputs and queries - get used as filenames - get used for logical control structures Here's a brief primer from someone who can explain it like a newbie, because when it comes to security, I only know so much. In other words this is a starting point, not the end-all-be-all, when it comes to web app security.

🔍

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