Search code examples
javascriptnode.jsexpressmiddlewaremulter

expressjs - how to require multer in another file


i use according to it's readme file in github
it's readme said call multer in like this:

app.js

var multer = require('multer')
app.post('/upload', upload.single('image'), function(req, res){})

but i defined my function(req, res) in another file - post.js - and my code in app.js looks like this:

app.post('/upload', upload.single('image'), post.new)

how can i require multer only on post.js, almost like this:

post.js

 var multer = require('multer')
 module.exports.new = function(req, res){
     //access to req.file
 }

app.js

 app.post('/upload', post.new)

Solution

  • I can think of two ways.

    Firstly, you could expose new as an array:

    module.exports.new = [upload.single('image'), function(req, res) {
        ...
    }];
    

    Secondly, you could use multer within your function:

    var imageUpload = upload.single('image');
    
    module.exports.new = function(req, res) {
        imageUpload(req, res, function(err) {
            // Put the rest of your code here
        });
    };
    

    In this second approach we're just invoking the multer middleware function ourselves, passing it our own function to use as the next callback. There's a little bit more information about doing this at https://github.com/expressjs/multer#error-handling though it describes the technique in a slightly different context.