gpt4 book ai didi

Node.JS Sharp 库 - 结束后写入错误

转载 作者:搜寻专家 更新时间:2023-11-01 00:31:24 25 4
gpt4 key购买 nike

我有以下代码:

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(transformer) 位时它才会工作。

知道我做错了什么吗?

最佳答案

您创建双工(可读和可写)流(转换器),它可用于不同的可读流(请求)。当您通过管道传输到转换器流时,它会关闭,稍后您将尝试再次通过管道传输到同一个关闭的流。

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

关于Node.JS Sharp 库 - 结束后写入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com