Benjamin
Benjamin

Reputation: 3826

Copying file using node.js with the possibility of cancellation

I am implementing a node.js application which copies an array of file paths, into an specific destination.

The method is simple, Let's say I have 10 file paths at the Origin paths, and 1 path as the destination path. so Each From path will be copied to the destination ONE By ONE using fs.copy function.

However, as the file array might be large in terms of number and size therefore I am trying to implement a feature which allows user to cancel the operation of copying files and removing whatever has been already copied.

My question is, Is it possible to have cancellation operation on fs.copy ? For example how can I stop fs.copy operation while it is trying to copy a 2GB file?

Is/Are there any alternatives besides fs.copy to achieve what I want?

Upvotes: 0

Views: 802

Answers (1)

Whothehellisthat
Whothehellisthat

Reputation: 2152

I guess you could just pipe a readsteam to a writestream, and the unpipe and unlink when you want to stop the copy and delete the destination file.

var from = fs.createReadStream(fromFilename)
  .pipe(to);
var to = fs.createWriteStream(toFilename)
  .on("unpipe", function() {
    fs.unlink(toFilename); // effectively deletes the file
  });

// triggered by user
from.unpipe(); // stops the copy, triggers the delete

Would that work?

Upvotes: 1

Related Questions