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.