2015-08-28 47 views
1

我有以下代碼:Node.js的夏普庫 - 結束錯誤後寫

var express = require('express'); 
var request = require('request'); 
var sharp = require('sharp'); 
var app = express(); 

var transformer = sharp() 
     .resize(100, 100) 
     .crop(sharp.gravity.north) 
     .on('error', function(err) { 
       console.log('ERR'); 
       console.log(err); 
     }); 


app.get('/test', function(req, res) { 
     var url = 'http://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg'; 
     request(url).pipe(transformer).pipe(res); 
}); 

var server = app.listen(3000, function() { 
     var host = server.address().address; 
     var port = server.address().port; 
     console.log('Listening at http://%s:%s', host, port); 
}); 

我第一次運行它,它工作正常。第二次運行它時,我得到[Error:write after end],這是在變壓器流的on('error')中發出的。

如果我只是做

request(url).pipe(res); 

它正常工作,所以當你包括.pipe(變壓器)位是唯一的。

任何想法我做錯了什麼?

回答

2

您創建雙工(可讀和可寫)流(轉換器),它可用於不同的可讀流(請求)。當你管到變壓器流時,它會被關閉,之後你會嘗試再次管道到相同的封閉流。

var transformer = sharp(); 
var stream = require('stream'); 

// transformer is a stream 
console.log("transformer instanceof stream.Duplex - ", transformer instanceof stream.Duplex); // true 


// just a simple streams example 
var readable = new stream.Readable(); 
var writable = new stream.Writable(); 

readable.push("data"); 
readable.push(null); 

writable._write = function (chunk, encoding, done) { 
    console.log("Writable stream received data: ", chunk.toString()); 
    done(); 
}; 

var _saved_original_end_method = writable.end; 
// redefining end method just to see if it's executed 
writable.end = function() { 
    console.log("Ending writable stream"); 

    _saved_original_end_method.apply(this, arguments); 
}; 

// first piping finished successfully 
readable.pipe(writable); 

var anotherReadableStream = new stream.Readable(); 

setTimeout(function() { 
    // this will cause an exception 
    anotherReadableStream.push("another data sample"); 
    anotherReadableStream.push(null); 
    anotherReadableStream.pipe(writable); 
}, 1000); 

結果:

transformer instanceof stream.Duplex - true 
Writable stream received data: data 
Ending writable stream 
events.js:85 
     throw er; // Unhandled 'error' event 
      ^
Error: write after end 
+1

所以......解決的辦法是爲每個'請求()'新'transformer',是你要什麼建議,對不對? ;-) – robertklep

+0

好吧,是的:)謝謝你的加入。 –

+0

謝謝,有助於澄清事情。我只是將變量聲明放在函數的範圍內,以便爲每個請求重新創建 - 很好地完成這項工作。 – richwol