Search code examples
javascriptnode.jsexpressmultipartmulter

Using multer cause error when running app


Im having node application with express which use multer module https://github.com/expressjs/multer

in the app.js file I put the following:

var mulStorage = require("./utils/store"),
    var upload = multer({
        storage: mul.storage,
        dest: 'uploads/'
    });
    app.use(upload.single('file'));

The store.js file look like following

var multer = require('multer');

var stor = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        var filename = file.originalname;
        var fileExtension = filename.split(".")[1];
        cb(null, Date.now() + "." + fileExtension);
    }
})
module.exports = {
    stor: stor
}

When I run request using postman I got the following error:

Error: ENOENT: no such file or directory, open 'c:\Users\c45669\WebstormProjects\App\uploads\1454935327214.zip'
   at Error (native)

Why multer doesn't create the folder if it doesn't exist??

If I'm creating the upload folder under the root manually this is working...

BTW, When I change the following and remove the storage: mul.storage, This is working, but I need the storage to determine the file name ...

    var upload = multer({
        //storage: mul.storage,
        dest: 'uploads/'
    });

Even If I remove the property dest from multer object and keep only the storage I got the same error...


Solution

  • Why multer doesn't create the folder if it doesn't exist??

    This is in documentation (link) :

    Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.

    I don't know why the author made this decision, but as you see this is not a bug.

    You can use fs module to create directories.