2015-08-21 169 views
1

我试图将pdfkit从png-js迁移到pngsj2,因为png-js不支持隔行png。我需要以同步方式加载PNG文件。我试图这样做:nodejs内存缓冲区同步.pipe()

var fs = require('fs'), 
    PNG = require('pngjs2').PNG; 
var stream = require('stream'); 
var bufferStream = new stream.PassThrough(); 
var buf = fs.readFileSync('./logs/rid12.png'); 
bufferStream.end(buf); 
var png = null; 
bufferStream.pipe(new PNG()) 
    .on('parsed', function() { 
     console.log("here"); 
     png = this; 
    }); 

console.log("there",png); 

“there”发生在“this”之前,所以png为null。是否有可能将内存缓冲区传递给PNG解析器,以便我不必制作回调体系结构?

回答

0

没有办法使异步方法同步。

有图书馆如https://github.com/scriby/asyncblock可能能够伪造它。

asyncblock(function(flow) { 

    var png = null 
    flow.sync(bufferStream.pipe(new PNG()) 
     .on('parsed', function() { 
     console.log("here"); 
     png = this; 
     flow.callback() 
     }) 
    ); 

    // png not null 
}); 
+0

我不这么认为。也许有可能调用某种方法(新的PNG()),但我不知道哪一个。 –