Question:
How can I write a new file in Nodejs?

Problem

I am writing a new file with the following code


const Image=req.body.Image;

const imageName = `frame_${Date.now()}.jpg`;

const imagePath = `../images/${imageName}`

const imageBuffer = Buffer.from(Image.replace(/^data:image\/\w+;base64,/, ''), 'base64');

fs.writeFile(imagePath, imageBuffer, (err) => {

    if (err) {

         console.error('Error saving image:', err);

    } else {

         console.log('Image saved:', imageName);

     }

});


The image path I am using is the image folder I have created for it .>image folder

is the file path wrong?


But the file is not created there and I am getting this output >error


What I am doing incorrectly in creating the file?


I want to create the file from datURL and store it in DB for further operations.


Solution

Have you tried using an absolute path using process.cwd()?

const imagePath = join(process.cwd(), 'images', imageName);


It's unclear where the root of your project is (where you are running node), and you need further directories before 'images'.


Answered by: >redwards

Credit: >StackOverflow


Blog Links: 

>How do I customize controller actions in Laravel Jetstream?

>Run Laravel Project to Active Local Server

>How to show encrypted user id in URL in Laravel?

>How to fix Laravel LiveWire listener?


Ritu Singh

Ritu Singh

Submit
0 Answers