Cloning a file using streams
suggest changeThis program copies a text file with a readable stream and a writable stream from createReadStream() and createWriteStream(). The utf8 encoding decodes the file as text, so this is not a byte-for-byte copy of a binary file. write() can return false when the buffer is full; pause until drain. Call end() so the copy is closed.
//Require the file System module
var fs = require('fs');
/*
Create readable stream to file in current directory (__dirname) named 'node.txt'
Use utf8 encoding
Read the data in 16-kilobyte chunks
*/
var readable = fs.createReadStream(__dirname + '/node.txt', { encoding: 'utf8', highWaterMark: 16 * 1024 });
// create writable stream
var writable = fs.createWriteStream(__dirname + '/nodeCopy.txt');
// Write each chunk of data to the writable stream
readable.on('data', function(chunk) {
if (!writable.write(chunk)) {
readable.pause();
}
});
writable.on('drain', function() {
readable.resume();
});
readable.on('end', function() {
writable.end();
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents