1

I am using express-file package. I use it like this:

const upload = require('express-fileupload');
app.use(upload({
    createParentPath: true
}));

This is how I store:

await req.files.main_image.mv('./public/images/movies/'+main_image);

I already have public/images directory created. I don't have movies directory in public/images directory though.

When It works: If I have /public/images/movies directory already created, it works

When it doesn't work: If I don't have /public/images/movies directory created, but have /public/images directory. Then it says:

ENOENT: no such file or directory, open 'C:\Users\glagh\Desktop\Work\MoviesAdviser\public\images\movies\1554741546720-8485.11521.brussels.the-hotel-brussels.amenity.restaurant-AD3WAP2L-13000-853x480.jpeg

What to do so that it automatically creates /movies directory and put the image there?

Nika Kurashvili
  • 6,006
  • 8
  • 57
  • 123

1 Answers1

1

Express-fileupload uses the following code to create the directory-path which you pass to the .mv function:

const checkAndMakeDir = function(fileUploadOptions, filePath){
  //Check upload options were set.
  if (!fileUploadOptions) return false;
  if (!fileUploadOptions.createParentPath) return false;
  //Check whether folder for the file exists.
  if (!filePath) return false;
  const parentPath = path.dirname(filePath);
  //Create folder if it is not exists.
  if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath); 
  return true;
};

The problem is that fs.mkdirSync() does not create the full path with the parent directories you specifiy (note that you'd use mkdir -p on the shell to create the whole folder structure) -> checkout How to create full path with node's fs.mkdirSync? for more information.

What you could do is use a module like fs-extra and use its function ensureDir which would create the corresponding parent directories (if they don't exist yet) before calling the .mv() function. Or in case you're node version is >= 10 use the native {rescursive:true} option which you can pass to fs.mkdirSync.

eol
  • 23,236
  • 5
  • 46
  • 64