我先这样写
fs.createReadStream(p).pipe(res);
没有问题,但是
var readable = fs.createReadStream(p); readable.on("data", function(data){ res.write(data); }); readable.on("end", function(){ // write response head res.writeHead(200, { "Content-Type": "text/html", "Transfer-Encoding": "chunked" }); res.end(); }); readable.on("error", function(){ res.statusCode = 500; res.end("500 Internal Error"); });
这样的话客户端就报出ERR_INVALID _CHUNKED_ENCODING 怎么回事呢?
8 回复
加了个buffer 问题没有了 谁能解释下是为什么吗 谢啦
var readable = fs.createReadStream(p); var buffer = new Buffer(""); readable.on("data", function(data){ // res.write(data); buffer = Buffer.concat([buffer, data]); }); readable.on("end", function(){ // write response head res.writeHead(200, { "Content-Type": "text/html", "Transfer-Encoding": "chunked" }); res.end(buffer); }); readable.on("error", function(){ res.statusCode = 500; res.end("500 Internal Error"); });
var readstream = fs.createReadStream(filepath,{encoding:’binary’}); res.write(data,’binary’); res.end()
ON(data)会被多次触发。这么写
var datax='';
var readable = fs.createReadStream(p,'binary');
readable.on("data", function(data){
datax +=data;
});
readable.on("end", function(){
// write response head
res.writeHead(200, {"Content-Type": "text/html" });
res.write(datax,'binary');
res.end();
});
readable.on("error", function(){
res.statusCode = 500;
res.end("500 Internal Error");
});