Created
September 20, 2020 00:39
-
-
Save shizuka-na-kazushi/56f1ba87f968886b8486824c35edc3a4 to your computer and use it in GitHub Desktop.
Readable.read()をProxyオブジェクトでトラップする
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
var fs = require('fs'); | |
var doSomethingWithTheStream = require('./dosomething'); | |
// readable streamはcreateReadStream関数がインスタンス化する | |
var readable = fs.createReadStream('image.jpg'); | |
var totalBytes = 0; | |
// readableのメンバー関数read()をProxyで置き換え | |
readable.read = new Proxy(readable.read, { | |
apply: (target, thisArg, argumentsList) => { | |
// 元の関数(read)の呼び出し | |
var bytes = target.apply(thisArg, argumentsList); | |
// 戻り値を使う | |
if (bytes) totalBytes += bytes.length; | |
return bytes; | |
} | |
}); | |
// 「何か」をする関数にオブジェクトを渡す | |
doSomethingWithTheStream(readable).then(() => { | |
console.log('All data read! = ' + totalBytes); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment