Skip to content

Commit fb0a6a1

Browse files
Hussein NasserHussein Nasser
authored andcommitted
readable
1 parent 24c4034 commit fb0a6a1

File tree

2 files changed

+13
-17
lines changed

2 files changed

+13
-17
lines changed

20-streams/201-raw-request-raw-read-stream.js

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
1-
const http = require("node:http");
1+
const http = require("node:https");
22
//request object is a writable stream
3-
const req = http.request("http://example.com", { "method": "GET"});
3+
//large json
4+
const req = http.request("https://raw.githubusercontent.com/json-iterator/test-data/refs/heads/master/large-file.json", { "method": "GET"});
45

56
req.on("response", res => {
67
//we tell node that we want to read this ourselves..
78
//for that we attach a readable event
9+
//this will be called everytime there is something to read
810
res.on("readable", ()=> {
911
let x = res.read();
10-
console.log(x.toString())
11-
//when read returns null we are done.
12-
while(x != null)
13-
{
14-
console.log(x.toString());
15-
x = res.read();
16-
}
12+
if (x == null) return; //quit if its null
13+
console.log(x.toString().length)
1714
})
1815
//call also assign an end event
1916
res.on("end", ()=>console.log("response fully read! "))

20-streams/202-raw-httpserver.js

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ const http = require("node:http");
44
//run with default, send this request
55
// head -c 10240000 /dev/zero | curl -X POST --data-binary http://192.168.7.179:8080
66
//then run with the overriden hwm
7-
//const server = http.createServer({"highWaterMark": 300_000} );
7+
const server = http.createServer({"highWaterMark": 300_000} );
88

9-
const server = http.createServer( );
9+
//const server = http.createServer( );
1010

1111
server.on("request", (req, res) => {
1212
//default is 65536
@@ -16,12 +16,11 @@ server.on("request", (req, res) => {
1616
//body is not read by default (can be large)
1717
req.on("readable", () => {
1818
function readChunk() {
19-
20-
//delay reading so we fill up the stream buffer.
21-
let chunk = req.read();
22-
if (chunk == null) return;
23-
console.log("reading..." + chunk.toString().length);
24-
}
19+
//delay reading so we fill up the stream buffer.
20+
let chunk = req.read();
21+
if (chunk == null) return;
22+
console.log("reading..." + chunk.toString().length);
23+
}
2524
//read every second so the _read is called
2625
setTimeout(readChunk, 1000);
2726

0 commit comments

Comments
 (0)