showing results for - "nodejs multipart 2fx mixed replace 3b boundary 3dboundarystring"
Emil
04 Aug 2020
1const webStream = {
2    get: function (url, callback) {
3        let webClient;
4
5        if (url.startsWith("http://")) {
6            webClient = require("http");
7        } else if (url.startsWith("https://")) {
8            webClient = require("https");
9        } else {
10            throw "Unsupported protocol.";
11        }
12
13        let clientRequest = webClient.get(url, function (response) {
14            let context = {
15                url: url,
16                boundary: "",
17                contentType: "",
18                contentLength: 0
19            };
20
21            let headersCompleted = false;
22            let bodyCompleted = false;
23            let buffer = null;
24            let receivedBodyChunk = 0;
25
26            response.on("data", function (chunk) {
27                if (!headersCompleted) {
28                    let headers = chunk.toString().split(/\r?\n/);
29
30                    context.boundary = headers[0].substring(2);
31                    context.contentType = headers[1].split(":")[1].trim();
32                    context.contentLength = parseInt(headers[2].split(":")[1]);
33
34                    buffer = Buffer.alloc(context.contentLength);
35
36                    headersCompleted = true;
37                } else {
38                    if (!bodyCompleted) {
39                        if (receivedBodyChunk < context.contentLength) {
40                            chunk.copy(buffer, receivedBodyChunk, 0, chunk.byteLength);
41
42                            receivedBodyChunk += chunk.byteLength;
43
44                            if (receivedBodyChunk === context.contentLength) {
45                                bodyCompleted = true;
46                            }
47                        }
48                    }
49
50                    if (bodyCompleted) {
51                        callback(buffer, context);
52
53                        headersCompleted = false;
54                        bodyCompleted = false;
55                        buffer = null;
56                        receivedBodyChunk = 0;
57                    }
58                }
59            });
60        });
61
62        return {
63            url: url,
64            handler: clientRequest,
65            on: function (type, listener) {
66                clientRequest.on(type, listener);
67            },
68            abort: function () {
69                clientRequest.abort();
70            }
71        };
72    }
73};
74
75let stream = webStream.get("http://127.0.0.1:8090/", function (data, context) {
76    // data: Received content (Buffer)
77    // context: { url, boundary, contentType, contentLength }
78
79    // TODO: Do something here...
80});
81
82// stream.abort();
83
84// stream.on("error", function(e) {
85//     console.log("Error: " + e.message);
86// });
87
similar questions