0

I try to copy a file with pipe but after code is run there is only an empty file. In the console is no error.

const writeStream = fs.createWriteStream( newLocation); // album1/fff28042018.jpg
writeStream.on('error', function(e){console.log(e)});

const readStream = fs.createReadStream(oldLocation); // imagesource/fff.jpg
readStream.on('error', function(e){console.log(e)});

readStream.pipe(writeStream);
writeStream.close();
readStream.close();

I expect that the image from imagesource/fff.jpg to the new file album1/fff28042018.jpg is copied. But in the end i have a new empty file album1/fff28042018.jpg

before the question comes up "Yes the source file exists".

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • Possible duplicate of [Fastest way to copy file in node.js](https://stackoverflow.com/questions/11293857/fastest-way-to-copy-file-in-node-js) – Charlie Jun 06 '19 at 05:50

1 Answers1

0

Looks like you are closing the streams before the data transferring finishes. Usually, when the readable finishes piping, it emits end on the writable stream and the stream get closed automatically.

Here is the shortest as cited in this answer.

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
Charlie
  • 22,886
  • 11
  • 59
  • 90