Created
December 30, 2020 01:58
-
-
Save midnightcodr/55b1dd65858da8ca0ccc522c8091001b to your computer and use it in GitHub Desktop.
Use stream.PassThrough to count file size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// node pass-the-fun-node-v14-and-under.js inputfile | |
// this will create a clone of inputfile with inputfile.bak | |
// and count the bytes written using stream.PassThrough | |
// note the simplified contructor form (as illustrated in | |
// pass-the-fun-node-v15.js does not work as expected in | |
// node v14 | |
const fs = require('fs') | |
const { pipeline, PassThrough } = require('stream') | |
const input = fs.createReadStream(process.argv[2]) | |
const out = fs.createWriteStream(process.argv[2] + '.bak') | |
class Counter extends PassThrough { | |
constructor (options) { | |
super(options) | |
this.length = 0 | |
} | |
_transform (chunk, encoding, callback) { | |
this.length += chunk.length | |
console.log(`this.length=${this.length}, read ${chunk.length} bytes`) | |
callback(null, chunk) | |
} | |
} | |
const counter = new Counter() | |
pipeline(input, counter, out, err => { | |
if (err) { | |
console.error(err) | |
} else { | |
console.log('done') | |
console.log(counter.length) | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const { pipeline, PassThrough } = require('stream') | |
const input = fs.createReadStream(process.argv[2]) | |
const out = fs.createWriteStream(process.argv[2] + '.bak') | |
const counter = new PassThrough({ | |
construct (callback) { | |
this.length = 0 | |
callback() | |
}, | |
transform (chunk, encoding, callback) { | |
this.length += chunk.length | |
console.log(`this.length=${this.length}, read ${chunk.length} bytes`) | |
callback(null, chunk) | |
} | |
}) | |
pipeline(input, counter, out, err => { | |
if (err) { | |
console.error(err) | |
} else { | |
console.log('done') | |
console.log(counter.length) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment