我是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
看起来数据停止而没有调用'end'。有趣的是,数据以大/小块的形式出现。
有什么想法吗?对二进制数据有明显的窒息吗?
node.js v0.10.7,表达v3.2.4,请求v2.21.0
答案 0 :(得分:3)
编辑:你有两个错误。
res.end
res.send
活动之前致电end
。以下是修改后的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);
});
});
使用该修复程序,所有测试文件都可以正常运行。