Skip to content

Commit d4d03e6

Browse files
vdiezjulien-f
authored andcommitted
implement stream backpressure
1 parent 80b74f0 commit d4d03e6

File tree

1 file changed

+26
-15
lines changed

1 file changed

+26
-15
lines changed

lib/api/createReadStream.js

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,21 +45,10 @@ module.exports = function createReadStream(path, options, cb) {
4545
});
4646
};
4747
}
48-
var running = false;
49-
stream._read = function(size) {
50-
if (running) {
51-
return;
52-
}
5348

54-
if (offset >= end) {
55-
return shouldClose
56-
? close(function() {
57-
stream.push(null);
58-
})
59-
: stream.push(null);
60-
}
49+
var running = false;
6150

62-
running = true;
51+
function read(size) {
6352
request(
6453
'read',
6554
{
@@ -69,15 +58,37 @@ module.exports = function createReadStream(path, options, cb) {
6958
},
7059
connection,
7160
function(err, content) {
72-
running = false;
7361
if (err != null) {
7462
return process.nextTick(stream.emit.bind(stream, 'error', err));
7563
}
7664

7765
offset += content.length;
78-
stream.push(content);
66+
if (stream.push(content)) {
67+
if (end - offset === 0) {
68+
running = false;
69+
stream.push(null);
70+
} else read(size);
71+
} else {
72+
running = false;
73+
}
7974
}
8075
);
76+
}
77+
stream._read = function(size) {
78+
if (running) {
79+
return;
80+
}
81+
82+
if (offset >= end) {
83+
return shouldClose
84+
? close(function() {
85+
stream.push(null);
86+
})
87+
: stream.push(null);
88+
} else {
89+
running = true;
90+
read(size);
91+
}
8192
};
8293
cb(null, stream);
8394
}

0 commit comments

Comments
 (0)