Search code examples
javascriptnode.jsexpressmiddleware

How to organize express middlewares better?


I'm using node with express and the following code is working as 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 to create upload folder: ' + err);
        }
        next();
    });
}, upload.single('file'));

My question is whether there is better way to write it? I mean to separate the function logic to other file and require it?


Solution

  • I whould suggest to 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 to create upload folder: ' + err);
                }
                next();
            });
        };
    }
    
    module.exports = {
        createFolderIfNotExists: createFolderIfNotExists
    };
    

    Then you can use it like:

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

    Not an ideal approach though. It is better to move initialization logic to separate script and run it at application startup, so that at the moment when you are expecting 'uploads' folder to exist in the filesystem - it will be there already.