I’m doing a project in Node.js using express. Here’s my directory structure:
root
|-start.js
|-server.js
|-lib/
| api/
| user_getDetails.js
| user_register.js
The lib/api/ directory has a number of JS files relating to the API. What I need to do is make a sort of hooking system, that whenever one of the API functions gets requested from the express HTTP server, it does whatever action is specified in the according API handler. It’s probably confusing, but hopefully you get the idea.
- Larry sends request via POST to get user details.
- Server looks in
lib/apito find the function associated with that request. - Server carrys out action and sends back data to Larry.
Hopefully you can help me out. I was thinking it could be done using prototypes, not sure though.
Thanks!
If you know where your scripts are, i.e. you have an initial directory, for example
DIR, then you can work withfs, for example:server.js
Now your scripts need to follow the following structure (because of the
require(path)(module_holder)line), for example:user_getDetails.js
and now, when handling a request, you do:
This should load all your modules to
module_holdervariable. I didn’t test it, but it should work (except for the error handling!!!). You may want to alter this function (for example makemodule_holdera tree, not a one level dictionary) but I think you’ll grasp the idea.This function should load once per server start (if you need to fire it more often, then you are probably dealing with dynamic server-side scripting and this is a baaaaaad idea, imho). The only thing you need now is to export
module_holderobject so that every view handler can use it.