[英]Streaming in Node.JS
I would like to know the good practice if I'm streaming data and want to have access to whole data after streaming; 我想知道优良的做法,如果我要流式传输数据,并希望在流式传输后可以访问整个数据;
I'm streaming like this: 我像这样流:
res._oldWrite = res.write;
res.write = function (chunk, encoding, cb) {
var decoded = chunk.toString(encoding);
write.write(new Buffer(decoded, encoding), encoding, cb);
return res._oldWrite.call(res, new Buffer(decoded, encoding), encoding, cb);
}
Now that I want to access to my data I did something like: 现在,我想访问我的数据,我做了如下操作:
res._oldWrite = res.write;
var jsonData = '';
res.write = function (chunk, encoding, cb) {
var decoded = chunk.toString(encoding);
jsonData += decoded;
write.write(new Buffer(decoded, encoding), encoding, cb);
return res._oldWrite.call(res, new Buffer(decoded, encoding), encoding, cb);
}
res.on('finish', function(){
// Now I can have access to jsopnData but it is gross ; what is the right way?
})
But isn't there any better way to do it? 但是没有更好的方法吗?
So I'm not 100% sure I understand your question @Web Developer, but since you asked for code, below is all that I meant. 因此,我不是100%肯定我理解您的问题@Web Developer,但是由于您要求输入代码,因此以下仅是我的意思。
Note that there are probably
other
shorter ways of doing the same thing (but I'm not sure what you mean by "access whole data after streaming" --- store in memory? all at once? etc): 请注意,可能还有
其他
更短的方法可以执行相同的操作(但是我不确定“流后访问整个数据”是什么意思-存储在内存中?一次全部?等等):
var dataStream = require('stream').Writable();
//I'm assuming the "real processing" is saving to a file
var fileStream = fs.createWriteStream('data.txt');
var masterStream = require('stream').Writeable();
masterStream._write = function (chunk, enc, next) {
dataStream.write(chunk);
fileStream.write(chunk);
next();
};
//if you now write to master stream, you get values in both dataStream and fileStream
//you can now listen to dataStream and "have access to the data"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.