javascript - How to organize express middlewares better? -


i'm using node express , following code working expected.

file app.js

app.use(function (req, res, next) {     fs.mkdir('uploads/', function (e) {         if (!!e && e.code !== 'eexist') {             console.log('error while trying create upload folder: ' + err);         }         next();     }); }, upload.single('file')); 

my question whether there better way write it? mean separate function logic other file , require it?

i whould suggest create file '{project_root}/middlewares/fsutils.js':

function createfolderifnotexists(folder) {     return function (req, res, next) {         fs.mkdir(folder, function (e) {             if (!!e && e.code !== 'eexist') {                 console.log('error while trying create upload folder: ' + err);             }             next();         });     }; }  module.exports = {     createfolderifnotexists: createfolderifnotexists }; 

then can use like:

var fsutils = require('./middlewares/fsutils');  app.use(fsutils.createfolderifnotexists('/uploads'), upload.single('file')); 

not ideal approach though. better move initialization logic separate script , run @ application startup, @ moment when expecting 'uploads' folder exist in filesystem - there already.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -