Search code examples
javascriptnode.jsuploadmulter

fs.readFileSync happening before multer uploaded files, ENOENT error


I am developing a platform where users should be able to create a hotel via an HTML form. Inside the form, there is an option to upload multiple image files.

I am using multer to handle the upload. My procedure is the following:

Create directory 'images'

  1. Save uploaded images in 'images' directory
  2. convert images in 'images' directory to base64
  3. save base64-format in an array
  4. save array in Hotel MongoDB Schema
  5. delete directory 'images'

The upload and saving work perfectly but I get an error when I try to upload the next hotel:

Error: ENOENT: no such file or directory, open 'C:\ ...'

The images are successfully stored in the 'images' directory, but obviously, as the app crashes, nothing is done with the files so I have to delete them manually.

As this is only happening on the second try (when restarting the application, it works again) I assume that fs.readFileSync is executed before the images are done uploading. I am clueless as multer is part of my router chain, the conversion to base64 should happen AFTER all files are uploaded to the server.

What am I doing wrong?

Multer functions: https://i.sstatic.net/Wz167.png Base64 conversion: https://i.sstatic.net/oOEmR.png Delete function (executed after saving to DB) https://i.sstatic.net/PlTvH.png


Solution

  • Here is a simple snippet to get images as a base64. Without storing them into the disk.

    const express = require('express');
    const multer  = require('multer');
    const storage = multer.memoryStorage();
    const upload = multer({ storage });
    
    const app = express();
    
    app.post('/submit', upload.array('images'), (req, res, next) => {
      // req.files is array of `images` files
      // I believe it is a `Buffer` object.
      const base64Images = req.files.map(image => buffer.toString('base64'));
      // Ready to save into DB;
      console.log(base64Images);
    })