1

Im trying to copy an png file from a folder to another folder in my nodeJs project.i have some problem. new Image file has some problem and cant open. i use this code

const  fs = require('fs');

     var inStr = fs.createReadStream(mainDir+"/"+req.body.ExRequestId+".png");

        var outStr = fs.createWriteStream(mainDir+"/"+docReq._id + ".png");

        inStr.pipe(outStr);
  • 1
    Try second method from [this](https://stackoverflow.com/questions/5212293/how-to-copy-a-image). If the same problem persists, then I guess you have some problem with the original image itself. – Ajay Dabas Jan 05 '20 at 06:12
  • @AjayDabas i try it but does not work. new image is empty – Badri Derakhshan Jan 05 '20 at 06:24
  • 1
    What version of Node are you using? Node added `copyFile` procedure from Node 8.5.0. Try to use it instead. Look [here](https://stackoverflow.com/questions/11293857/fastest-way-to-copy-file-in-node-js) to find out how. – Armin Taghavizad Jan 05 '20 at 08:16
  • @ArminTaghavizad v11.0.9 when i use copyFile , it done but its empty and does not have any data to show image – Badri Derakhshan Jan 05 '20 at 08:34
  • 1
    If you're using a lower version of node <= 8.5.0 you can use this package which extends the native `fs` module. https://www.npmjs.com/package/fs-extra. This is a very common and popular package. – Naor Levi Jan 05 '20 at 12:09

2 Answers2

2

When working with streams, it's good practice to wait for streams to become ready before using them and handle the errors.

The following snippet waits for the ready event on both streams before piping the ReadStream to the WriteStream and handles the errors.

// assuming you're using express and the app instance is bound to a variable named app

const fs = require('fs');
const path = require('path');    

// ...

// helper function: returns a promise that gets resolved when the specified event is fired
const waitForEvent = (emitter, event) => new Promise((resolve, reject) => emitter.once(event, resolve));

app.post('/handle-post', async (req, res) => {
    // TODO: validate the input
    const { ExRequestId } = req.body;

    const srcFileName = `${path.join(mainDir, ExRequestId)}.png`;
    const destFileName = `${path.join(mainDir, docReq._id)}.png`;

    const srcStream = fs.createReadStream(srcFileName);    
    await waitForEvent(srcStream, "ready");
    const destStream = fs.createWriteStream(destFileName);    
    await waitForEvent(destStream, "ready");

    const handleError = err => res.status(500).json(err);
    srcStream.on("error", handleError);
    destStream.on("error", handleError);

    srcStream.pipe(destStream);
    await waitForEvent(srcStream, 'end');

    res.status(200).json({srcFileName, destFileName});
});

I also put together a minimal working example. It can be found here.

fardjad
  • 20,031
  • 6
  • 53
  • 68
1

try with this code:

fs.readFile(sourcePath , function (err, data) {
 if (err) throw err;
 fs.writeFile(destinationPath , data , 'base64' , function (err) {
  if (err) throw err;
   console.log('It\'s saved!');
 });
});