要在不缓冲的情况下将附件从 cradle 传输到客户端,您可以通过管道将其readableStream传输到响应的writableStream。
长版
摇篮的变体db.getAttachment
返回 a readableStream
(请参阅从摇篮的文档流式传输)。res
另一方面,express'对象用作writableStream
. 这意味着您应该能够* 像这样通过管道将附件连接到它:
// respond to a request like '/preview/?doc=xxxxxx&image=img1.jpg'
app.get('/preview/', function(req, res){
// fetch query parameters from url (?doc=...&image=...)
var id = req.query.doc
var filename = req.query.image
// create a readableStream from the doc's attachment
var readStream = db.getAttachment(id, filename, function (err) {
// note: no second argument
// this inner function will be executed
// once the stream is finished
// or has failed
if (err)
return console.dir(err)
else
console.dir('the stream has been successfully piped')
})
// set the appropriate headers here
res.setHeader("Content-Type", "image/jpeg")
// pipe the attachment to the client's response
readStream.pipe(res)
})
或者,稍微短一点:
app.get('/preview/', function(req, res){
res.setHeader("Content-Type", "image/png")
db.getAttachment(req.query.doc, req.query.image, someErrorHandlerFunction).pipe(res)
})
*我不在工作,所以很遗憾我无法验证此代码是否会运行。如果您有问题,请给我留言。