node.js服务器不接收所有的二进制数据(或客户端不发送所有的二进制数据)
我对node.js非常陌生,并且遇到了一个可能非常基本的问题,我相信我只是没有“获取”某些东西,但是我们继续:
我有两个节目…
- server.js是一个简单的express / node.js服务器,它接受二进制数据的POST
- client.js是一个简单的request / node.js客户端,它将大文件的内容传输到服务器
我一直在淘洗stackoverflow的build议,我想我有一个小问题的例子:
客户:
var fs = require('fs'); var request = require('request'); fs.createReadStream('test2.zip').pipe(request.post('http://localhost:3000/'));
服务器:
var express = require('express'); var app = express(); app.post('/', function(req, res){ var size = 0; req.on('data', function (data) { size += data.length; console.log('Got chunk: ' + data.length + ' total: ' + size); }); req.on('end', function () { console.log("total size = " + size); }); req.on('error', function(e) { console.log("ERROR ERROR: " + e.message); }); res.send("Thanks"); }); app.listen(3000); console.log('Listening on port 3000');
当我发送一个小文件,或者如果我从一个外部客户端,如在Chrome中的高级REST客户端POST数据我看到我所期望的:
Got chunk: 481 total: 481 total size = 481
但是,如果我发送一个大文件,我看到一堆数据通过,然后停止:
Got chunk: 65405 total: 65405 Got chunk: 131 total: 65536 Got chunk: 65396 total: 130932 Got chunk: 140 total: 131072 Got chunk: 65387 total: 196459 Got chunk: 149 total: 196608 Got chunk: 65378 total: 261986 Got chunk: 158 total: 262144 Got chunk: 65369 total: 327513 Got chunk: 167 total: 327680 Got chunk: 65360 total: 393040 Got chunk: 176 total: 393216 Got chunk: 65351 total: 458567 Got chunk: 185 total: 458752 Got chunk: 65342 total: 524094 Got chunk: 194 total: 524288 Got chunk: 65333 total: 589621 Got chunk: 203 total: 589824 Got chunk: 65324 total: 655148 Got chunk: 212 total: 655360 Got chunk: 15898 total: 671258
它看起来像数据停止没有“结束”被调用。 数据以大块/小块forms出现也是有趣的。
有任何想法吗? 高速窒息的二进制数据?
node.js v0.10.7,express v3.2.4,请求v2.21.0
编辑 :你有2个错误。
- 永远不要呼吁
res.end
- 在获取
end
事件之前调用res.send
。
这是修改过的server.js
代码片段,其中res.end
行是有趣的移动/改变。
app.post('/', function(req, res){ var size = 0; req.on('data', function (data) { size += data.length; console.log('Got chunk: ' + data.length + ' total: ' + size); }); req.on('end', function () { console.log("total size = " + size); res.end("Thanks"); }); req.on('error', function(e) { console.log("ERROR ERROR: " + e.message); }); });
有了这个修补程序,所有的小工具和大工具都可以正常工作。