Home > Back-end >  Node.js does multer with diskStorage create a folder if it doesn't exist?
Node.js does multer with diskStorage create a folder if it doesn't exist?

Time:06-30

I have a small app that receives via POST a file and stores it in a specific folder.

I know that this line:

const multer = multer({ dest: ‘media' }) 

(of course with some more code, where I use the multer.single('somefilename')) will create a new folder named media if it doesn't exist already.

But I want to be able to control the name given to the file and some other stuff, so I'm using it with diskStorage instead:

const x = multer.diskStorage({
  destination: function (req, file, cb) {
     cb(null, 'media')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
})

const multer = multer({ storage: x })

(there's some more code of course with multer.single('somefilename'))

It works fine when the folder 'media' already exists, but doesn't create it if it doesn't - is it supposed to, or only the simpler multer can do that?

Thanks in advance!

CodePudding user response:

It won't create the folder, they warn that in the official doc:

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.

Below is an example of how to create the entire path, but exist many alternatives:

const path = require("path");
const shell = require('shelljs');

const fullPath = path.join(__dirname, '..', '..', "uploads");
shell.mkdir('-p', fullPath);

As @robertklep suggest, please consider: fs.mkdir() instead of shell:

fs.mkdir(path.join(__dirname, 'test'), { recursive: true })
  • Related