fs.readFileSync happening before multer uploaded files, ENOENT error - javascript

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'
Save uploaded images in 'images' directory
convert images in 'images' directory to base64
save base64-format in an array
save array in Hotel MongoDB Schema
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.stack.imgur.com/Wz167.png
Base64 conversion: https://i.stack.imgur.com/oOEmR.png
Delete function (executed after saving to DB) https://i.stack.imgur.com/PlTvH.png

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);
})

Related

Error Enoent: no such file or directory multer

I was building a twitter clone app where users can upload tweets with and without images. Before deploying my backend, everything worked fine. Users could upload tweets with and without images. However, after I deployed my backend, I've been unable to get users to upload a tweet with an image. I keep getting this error.
Error Enoent: no such file or directory
This happened after I deployed my backend to Render. It was working fine just before I deployed my backend It is currently impossible to upload an image at the moment. I think this has something to do with the way I'm setting the path in my multer middleware. Here's the middleware I use to upload images:
import multer from "multer";
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads");
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
const uploadFile = multer({ storage }).single("image");
export default uploadFile;
As you can see, I'm setting the storage path to "uploads". However, since I've deployed my backend somewhere else, I think it should be updated. Can anyone tell me how I should update it if I already have a backend hosted somewhere else. If I'm wrong and it has nothing to do with how I'm setting the path, can you tell me what's wrong and how to fix it? Thanks a lot!

How do I get an image to postman using Express.js?

I have some jpeg and png photos in my local machine. How do i show them on my postman using express.js?
Do I use sendFile?
And is it possible to print more than one photo?
Here is a template
app = require("express")();
app.get("/", (req, res) => {
res.send("I want to send the image here")
})
Same Question as How do I get image/file data on postman using get method?
One simple way to do this is to serve the files statically by using express static middleware.
Assuming your images reside in a uploads folder in your app's root, you'd simply add to your express app:
app.use("/uploads", express.static('uploads'))
You can then request it through postman/browser with GET http://your-host/uploads/name-of-image.png.

show or read all files and folder present in os or system using electron

I am new to electron and I wanted to develop a file explorer (cross platform application for desktop) using electron.
I am unable to read root folder.
How can i read root folder in windows, Linux and mac ?
I tried the following code but it resulted in an error:
const fs = require('fs');
const fileUrl = new URL('file:///Desktop');
fs.readFileSync(fileUrl);
if you want to read all files in a directory you should use another function in fs called fs.readdir or fs.readdirSync
// Callback
fs.readdir('/home/guest/projects', (err, files) => {
console.log(files);
})
// Sync
fs.readdirSync('/home/guest/projects')

In which directory should I save uploaded files for MERN Stack?

I'm using the Mern stack, but I'm having an issue as to where to save uploaded files. Let me explain.
I have a form that sends over a formdata which includes a .jpg image.
On Node/express side, I receive it well. But now I'm stuck.
I'm using express-fileupload package which attaches an mv function that allows me to store my file in a directory.
In my endpoint, I have this snippet:
const img1= req.files.image1;
const img1Name = img1.name;
img1.mv("NOT-SURE-WHERE-TO-MAKE-MY-DIRECTORY"+img1Name, (err) => {
if (err) {
return res.status(500).json({message: 'Could Not mv file'});
} else {
return res.status(200).json({message: 'mv done'});
}
})
Where do I create the directory to store the .jpg image?
Do I create it in the client's src? or client's public?
Or, do I run the npm-run-build command to create my build folder and then point my mv function to save the file in there?
create a static file middleware in node app.js file to public directory then # public/images
If not try using multer it is much easier to upload Files

Node.js express res.download and res.attachment don't changes filename

express 4.13
node.js 5.7.0
I am trying to make resposne to user with renamed file.
Archive.findById(req.params.id, function(err, file) {
res.download(file.path, "justfile.docx");
});
This code doesn't working. When i use it, file downloaded with default name, not with "justfile.docx".

Categories