Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parsing the response from HTTP requests #90

Open
david1602 opened this issue Apr 26, 2020 · 0 comments
Open

Parsing the response from HTTP requests #90

david1602 opened this issue Apr 26, 2020 · 0 comments
Labels
new feature request new feature request

Comments

@david1602
Copy link

I have noticed the HTTP module only returns a raw HTTP response string. I really wanted to use it for... reasons, so I have written a very rudimentary parser. Maybe this could be improved and/or (as an option) built into the HTTP module?

const isJSON = function (test) {
    try {
        JSON.parse(test);
        return true;
    } catch (e) {
        return false;
    }
};
function parseBody(body) {
    if ('string' !== typeof body) throw new Error('body to parse must be a string');

    if (!body.startsWith('HTTP/1.1')) throw new Error('Unexpected response: ' + body);

    // Here we can start parsing
    const obj = { headers: {}, body: '' };

    const splitter = body.indexOf('\r\n') !== -1 ? '\r\n' : '\n';

    const chunks = body.split(splitter);

    let IS_HEADER = true;

    for (let i = 0; i < chunks.length; i++) {
        const curr = chunks[i];
        if (i === 0) {
            const [, statusCode, status] = curr.match(/HTTP\/1\.1 (\d{3}) (.+)/);
            obj.status = {
                statusCode: statusCode,
                status: status
            };
        } else {
            if (IS_HEADER) {
                if ('' === curr) IS_HEADER = false;
                else {
                    const headerParts = curr.split(': ');
                    obj.headers[headerParts[0]] = headerParts[1];
                }
            } else {
                obj.body = obj.body + curr;
            }
        }
    }

    if (isJSON(obj.body)) obj.body = JSON.parse(obj.body);

    return obj;
}
@theBGuy theBGuy added the new feature request new feature request label Mar 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new feature request new feature request
Projects
None yet
Development

No branches or pull requests

2 participants