2015-10-16 154 views
0

我想知道如果流式传输数据并希望在流式传输后访问整个数据的良好做法;在Node.JS中流式传输

我流是这样的:

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); 
    } 

现在,我要访问我的数据我不喜欢的东西:

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? 
    }) 

但是是不是有什么更好的办法来做到这一点?

+0

因此,您正在将数据流式传输到可写入流并希望访问该数据?你为什么不在你的自定义流中流到另一个流?然后你可以添加一个列表到第二个流来获取数据。 –

+0

对不起,我没有明白你的意思,你可以告诉我你的解决方案在我的代码中... –

+0

你应该**从流**中读取,而不是拦截'.write()'调用它! – Bergi

回答

0

所以我不是100%确定我理解你的问题@Web Developer,但是因为你问了代码,下面是我的意思。

请注意,有可能 其他 做同样的事情的更短的方式(但我不知道你的意思是“流式传输后访问整个数据” - 一次全部存储在内存中)等等) :

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"