In Node.js, you can detect when a readable stream has finished transferring data to a writable stream by listening for the finish
event on the writable stream. The finish
event is emitted when all data has been flushed to the underlying system.
Here's how you can do it:
javascriptconst fs = require('fs');
// Create a readable stream
const readableStream = fs.createReadStream('input.txt');
// Create a writable stream
const writableStream = fs.createWriteStream('output.txt');
// Pipe the data from the readable stream to the writable stream
readableStream.pipe(writableStream);
// Listen for the 'finish' event on the writable stream
writableStream.on('finish', () => {
console.log('Data transfer completed.');
});
In this example, we create a readable stream using fs.createReadStream
to read data from the file "input.txt." Then, we create a writable stream using fs.createWriteStream
to write data to the file "output.txt." We use the pipe
method to pipe the data from the readable stream to the writable stream.
Finally, we listen for the finish
event on the writable stream. When all data has been written to the "output.txt" file, the finish
event will be emitted, and the callback function will be executed, printing "Data transfer completed." to the console.
This approach is especially useful when dealing with large files or network operations, as it allows you to be notified when the data transfer is complete and when it is safe to perform further actions with the written data.