Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register Helper functions Node.JS + Express

Im trying to learn NodeJS and Express. Im using the node-localstorage package to access the localstorage. This works when using the code directly in the function like this

routes/social.js

exports.index = function(req, res)
{
     if (typeof localStorage === "undefined" || localStorage === null) 
     {
        var LocalStorage = require('node-localstorage').LocalStorage;
        localStorage = new LocalStorage('./scratch');
     }

localStorage.setItem('myFirstKey', 'myFirstValue');
console.log(localStorage.getItem('myFirstKey'));
res.render('social/index', {title: "Start"});
}

But I don't want to write this code over and over again in all my other functions when accessing the localstorage. I want to be able to register a helper function that I can access like

 var localStorage = helpers.getLocalStorage

or something like that.

How can I do this in NodeJS? I've seen something about app.locals? But how can I access the app object in my routes?

like image 215
JOSEFtw Avatar asked Jun 23 '13 11:06

JOSEFtw


1 Answers

There are many ways to do this, depending on how/where you are planning to use your helper methods. I personally prefer to set my own node_modules folder, called utils, with all the helpers and utility methods I need.

For example, assuming the following project structure:

app.js
db.js
package.json
views/
   index.ejs
   ...
routes/
   index.js
   ...
node_modules/
   express/
   ...

Simply add a utils folder, under node_modules, with a index.js file containing:

function getLocalStorage(firstValue){
   if (typeof localStorage === "undefined" || localStorage === null) 
   {
      var LocalStorage = require('node-localstorage').LocalStorage;
      localStorage = new LocalStorage('./scratch');
   }
   localStorage.setItem('myFirstKey', 'myFirstValue');
   return localStorage;
}
exports.getLocalStorage = getLocalStorage;

Then, anytime you need this function, simply require the module utils:

var helpers = require('utils');
exports.index = function(req, res){
  localStorage = helpers.getLocalStorage('firstValue');
  res.render('social/index', {title: "Start"});
}

EDIT As noted by Sean in the comments, this approach works as long as you name your node_modules folder with a name different from Node's core modules. This is because:

Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name.

like image 53
verybadalloc Avatar answered Oct 11 '22 19:10

verybadalloc