Jhon D February 2016

Node app.js use function how its recommended

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

I need to use as middelware the following code

var upload = multer({
    storage: storage
});

app.use(upload.single('file'));

app.use('/', rot, function (req, res, next) {
    next();
});

But before the var upload = multer... I want to run the following code

var mkdirSync = function (path) {
    try {
        fs.mkdirSync(path);
    } catch(e) {
        if ( e.code != 'EEXIST' ) throw e;
    }
}


mkdirSync( 'uploads/');

How should I do it nicely? add the code of mkdir before the upload multer

Answers


RIYAJ KHAN February 2016

Its better to do like this.

//dir.js

exports.makeDir = function(path) {

    console.log(path);
    try {
        fs.mkdirSync(path);
    } catch (e) {
        if (e.code != 'EEXIST') throw e;
    }
}

And in your app.js

var varMkDir = require('./dir');


app.use(varMkDir.makeDir('uploads/'));

EDIT :

app.use(function(){

    varMkDir.makeDir('uploads/');
})


wjohnsto February 2016

You can create another middleware for this 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 you pass an error into the next middleware, express will know to skip all the following middleware functions and go straight to the error handler.

EDIT: I would recommend using the non-sync version of mkdir, and avoiding the try/catch block altogether.

EDIT 2: Maybe I am mistaken, and all you are looking to do is make sure the storage directory exists? If this is the case then simply doing the following will work:

mkdirSync(storage);

var upload = multer({
    storage: storage
});

app.use(upload.single('file'));

app.use('/', rot, function (req, res, next) {
    next();
});

Post Status

Asked in February 2016
Viewed 3,232 times
Voted 5
Answered 2 times

Search




Leave an answer