我对 node.js 很陌生,并且遇到了一个可能非常基本的问题,我确定我只是没有“得到”一些东西,但是我们开始吧:
我有两个程序...
- server.js 是一个简单的 express/node.js 服务器,它接受二进制数据的 POST
- client.js 是一个简单的 request/node.js 客户端,它将大文件的内容流式传输到服务器
我一直在搜寻 stackoverflow 的建议,我想我有一个关于这个问题的小例子:
客户:
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 客户端)发布数据时,我会看到我所期望的:
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
看起来数据停止而没有调用“结束”。数据以大/小块的形式出现也很有趣。
有任何想法吗?是否对二进制数据感到窒息?
node.js v0.10.7, express v3.2.4, request v2.21.0