Node.js流

时间:2013-11-16 18:01:44

标签: javascript node.js

我使用节点js的zlib组件来使用

来收集数据
var stream = zlib.createDeflate({ "level": level });                             
stream.write(string);                                                            
stream.on('data', function(data) {console.log(data.toString())});

但是,数据回调仅使用缓冲区“x”运行一次。我想要的是将流中的缩小数据提取到变量中,异步或非异步。我发现的所有流的例子都是在流之间写入数据。

2 个答案:

答案 0 :(得分:0)

试试这个

var stream = zlib.createDeflate({ "level": level });             
var buffers = [];
var result;                
stream.on('data', function(data) {buffers.push(data)});
stream.on('close', function() {  
    result = Buffer.concat(buffers);
    console.log('COMPRESSED DATA:', result);  
})

stream.write(string);
stream.end();

答案 1 :(得分:0)

我最终使用

  function deflate(string, level) {

  var fiber = fibers.current;

  var result = [];

  var out = new stream.Stream();

  out.write = function(data) {
    result.push(data);
  }

  out.end = function() {
    result = Buffer.concat(result);
    fiber.run(result.toString('base64'));
  }

  var deflate = zlib.createDeflate({ "level": level });
  deflate.end(string, 'utf8');
  deflate.pipe(out);

  return fibers.yield();
}