使用socket.io将文件从string发送到浏览器

我在一个node.js项目中使用PDFKit和socket.io来生成一个pdf,当用户点击前端的一个button时。 如何从这里stream式传输或以其他方式将最终的PDF发送给最终用户? 我宁愿避免保存文件到文件系统,然后不得不删除它,如果我可以…希望以某种方式stream。

socket.on('customerRequestPDF', function(){ doc = new PDFDocument; doc.text('Some text goes here', 100, 100); //I could do this but would rather avoid it doc.write('output.pdf'); doc.output(function(string) { //ok I have the string.. now what? }); }); 

websocket并不是提供PDF的合适机制。 只需使用常规的HTTP请求。

 // assuming Express, but works similarly with the vanilla HTTP server app.get('/pdf/:token/filename.pdf', function(req, res) { var doc = new PDFDocument(); // ... doc.output(function(buf) { // as of PDFKit v0.2.1 -- see edit history for older versions res.writeHead(200, { 'Content-Type': 'application/pdf', 'Cache-Control': 'private', 'Content-Length': buf.length }); res.end(buf); }); }); 

现在警告一下:这个PDF库已经坏了。 从版本0.2.1开始,输出是一个适当的Buffer ,但它在内部使用不推荐使用的binarystring编码,而不使用Buffer s。 (以前的版本给了你二进制编码的string。)从文档 :

'binary' – 通过仅使用每个字符的前8位将原始二进制数据编码为string的一种方法。 此编码方法已弃用,应尽可能避免使用Buffer对象。 此编码将在未来版本的Node中删除。

这意味着当节点删除二进制string编码时,库将停止工作。