我正在尝试学习NodeJS和Express.我使用node-localstorage包来访问localstorage.这在直接在这样的函数中使用代码时有效
路线/ 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"}); }
但是,在访问localstorage时,我不想在所有其他函数中反复编写此代码.我希望能够注册一个我可以访问的辅助函数
var localStorage = helpers.getLocalStorage
或类似的东西.
我怎样才能在NodeJS中做到这一点?我见过关于app.locals的一些事情?但是如何在路线中访问app对象?
解决方法
有很多方法可以执行此操作,具体取决于您计划使用辅助方法的方式/位置.我个人更喜欢用我需要的所有帮助器和实用程序方法设置我自己的node_modules文件夹,名为utils.
例如,假设以下项目结构:
app.js db.js package.json views/ index.ejs ... routes/ index.js ... node_modules/ express/ ...
只需在node_modules下添加一个utils文件夹,其中包含一个index.js文件,其中包含:
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;
然后,只要您需要此功能,只需要模块utils:
var helpers = require('utils'); exports.index = function(req,res){ localStorage = helpers.getLocalStorage('firstValue'); res.render('social/index',{title: "Start"}); }
编辑
正如Sean在评论中所指出的,只要您将node_modules文件夹命名为不同于Node’s core modules的名称,此方法就可以工作.这是因为:
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.