我有以下代码:
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);
});
我第一次运行它工作正常。我第二次运行它得到[错误:结束后写入],这是在变换器流中的on('error')中发出的。
如果我这样做
request(url).pipe(res);
它工作正常,所以只有当你包含.pipe(变换器)位时才会这样。
任何想法我做错了什么?
答案 0 :(得分:4)
您可以创建双工(可读和可写)流(变换器),它可用于不同的可读流(请求)。当您管道到变换器流时,它会被关闭,之后您会尝试再次管道到同一个封闭的流。
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