带有CouchDB附件的服务文件



我使用Express。我不知道如何发送一个图像文件到客户端,它将显示到HTML标签<img src='/preview/?doc=xxxxxx&image=img1.jpg'>。我使用Cradle getAttachment函数与Couchdb通信https://github.com/flatiron/cradle

db.getAttachment(id, filename, function (err, reply) {
    set('Content-Type', 'image/png');
    res.end(reply);
});

我不知道reply到底是什么,以及如何将该图像传输到客户端没有缓冲区

要在没有缓冲的情况下将附件从摇篮传输到客户端,可以readableStream管道到响应的writableStream

长版本

cradle的db.getAttachment的一个变体返回readableStream(参见cradle的文档流)。另一方面,express' res对象充当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)
})

*我不在工作,所以很遗憾我不能验证这个代码是否会运行。

最新更新