javascript - Node app.js use function how its recommended -


im having node app using express i've server.js app.js etc

i need use middelware following code

var upload = multer({     storage: storage });  app.use(upload.single('file'));  app.use('/', rot, function (req, res, next) {     next(); }); 

but before var upload = multer... want run following code

var mkdirsync = function (path) {     try {         fs.mkdirsync(path);     } catch(e) {         if ( e.code != 'eexist' ) throw e;     } }   mkdirsync( 'uploads/'); 

how should nicely? add code of mkdir before upload multer

you can create middleware purpose, since app.use accepts multiple middleware functions.

app.use(function(req, res, next) {     fs.mkdir(path, function(e){         if(!!e && e.code !== 'eexist'){             next(e);             return;         }         next();     }); }, upload.single('file')); 

the above code should work. when pass error next middleware, express know skip following middleware functions , go straight error handler.

edit: recommend using non-sync version of mkdir, , avoiding try/catch block altogether.

edit 2: maybe mistaken, , looking make sure storage directory exists? if case doing following work:

mkdirsync(storage);  var upload = multer({     storage: storage });  app.use(upload.single('file'));  app.use('/', rot, function (req, res, next) {     next(); }); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -