在将文件传输到客户端之后,res.end()不会被发送

我基本上是试图从MongoDb文件stream到客户端。 该文件接收没有问题,但是当stream结束,我尝试发送request.end()客户端永远不会得到它。

app.post('/upload', function (req, res) { var db = new mongo.Db('prueba', new mongo.Server("127.0.0.1", 27017)); db.open(function (err) { if (err) return handleError(err); var gfs = Grid(db, mongo); console.log(req.filename); var uploadedSize = 0, uploadProgress = 0; idPdf = new ObjectId(); //cliente crea un id de mongo, el cual se utilizara para traer el recurso despues console.log(idPdf); var grabarm = req.pipe(gfs.createWriteStream({ filename: 'test', _id: idPdf })); grabarm.on("close", function () { var tbuffer = gfs.createReadStream({filename: 'test'}); tbuffer.on('open', function () { // This just pipes the read stream to the response object (which goes to the client) res.setHeader('Content-disposition', 'attachment; filename=pdfmongo.pdf'); res.setHeader('Content-type', 'application/pdf'); tbuffer.pipe(res); }); tbuffer.on('data', function (chunk) { console.log("receiving data"); }); tbuffer.on("close", function () { console.log("fin"); //can see it in console res.end("ok file received");//client never sees this }); tbuffer.on('error', function (err) { res.end(err); }); }); }); }); 

当您的可读stream完成读取时,默认情况下,它将发出和end()事件,这将调用可写入stream(resstream)上的end()事件。 在这种情况下,您不必担心调用end()。

因此,在调用end()事件之后,res将不再可写。 所以,如果你想保持它可写,只需将结束:false选项传递给pipe()。 举个例子:

 fs.createReadStream("./image.png").pipe(res, { end: false }); 

,然后稍后再调用end()事件。

顺便说一句,你应该听“结束”事件,而不是“closures”事件stream完成因为“closures”并不明确意味着所有的数据已被转移。