如何从Node.JS套接字stream触发浏览器下载?

我的node.js应用程序连接通过var socket = net.createConnection(port, ip); 从另一台服务器下载文件。 一旦build立连接,服务器将把文件作为数据发送。

我接着做了

 socket.on('data', function(data) { }).on('connect', function() { }).on('end', function() { console.log('DONE'); }); 

我最初的目标是使用上述方法下载文件,同时将字节作为可下载文件提供给客户端的浏览器。 例如:用户点击网站上的一个button触发服务器端下载function,用户得到文件保存提示。 Node.JS然后从远程服务器下载文件,同时在浏览器客户端给用户每个新的字节。 这可能吗? 我想它将需要发送八位字节stream的头来触发浏览器Node.JS之间的文件传输。 但是,如何?

更新

现在我试着下面的代码在下面的答案帮助:

 app.get('/download', function (req, res) { res.setHeader('Content-disposition', 'attachment; filename=' + "afile.txt"); res.setHeader('Content-Length', "12468") var socket = net.createConnection(1024, "localhost"); console.log('Socket created.'); socket.on('data', function(data) { socket.pipe(res) }).on('connect', function() { // // Manually write an HTTP request. // socket.write("GET / HTTP/1.0\r\n\r\n"); }).on('end', function() { console.log('DONE'); socket.end(); }); }); 

数据正在作为一个下载被发送到用户的浏览器,但最终的结果是一个破碎的文件。 我检查了内部的内容,它看到一些沿着过程的东西导致文件损坏。 我想现在我必须写每个字节的字节? 而不是做socket.pipe?

您需要在您的http响应中设置content-disposition标题:

  response.writeHead(200, { 'Content-Disposition': 'attachment; filename=genome.jpeg; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"' }); yourDataStream.pipe(response); 

请参阅RFC2183

看起来你可能想要这个:

 app.get('/download', function (req, res) { res.attachment('afile.txt'); require('http').get('http://localhost:1234/', function(response) { response.pipe(res); }).on('error', function(err) { res.send(500, err.message); }); }); 

我find了解决scheme! 通过做res.write(d)我能够从其他连接的字节指向用户浏览器下载。 app.get('/ download',函数(req,res){

 res.setHeader('Content-disposition', 'attachment; filename=' + "afile.jpg"); res.setHeader('Content-Length', "383790"); res.setHeader('Content-Type','image/jpeg'); var socket = net.createConnection(1024, "localhost"); console.log('Socket created.'); //socket.setEncoding("utf8"); socket.on('data', function(d) { console.log(d); res.write(d); }).on('connect', function() { // // Manually write an HTTP request. // socket.write("GET / HTTP/1.0\r\n\r\n"); }).on('end', function() { console.log('DONE'); socket.end(); }); });