Node.js HTTP request: how to determine the body of the response body?

I use https.request()to make an HTTPS request using the following familiar pattern:

var request = https.request(options, function (response) {
    var chunks = [];
    response.on('data', function (chunk) {
        chunks.push(chunk);
    });

    response.on('end', function () {
        var buffer = Buffer.concat(chunks);
        ...
    });
});
...
request.end();
...

Once I have the answer ready Buffer, it should be packed into a JSON object. The reason for this is because I am creating a tunnel in which the HTTP response (its headers, status and body) must be sent as JSON via another protocol.

, , , , , Buffer Base64 ( buffer.toString('base64')) unencode new Buffer(theJsonObject.body, 'base64'). , , Base64, , HTTP- (, ). https.request(), , chunk.toString() JSON UTF-8. JSON, , , , "" UTF-8 (, .htm,.css ..) Base64 (, ).

, MIME content-type, , . , " " , , , UTF-8 (, "text/html" ..). (, , "image/png" ) Base64.

- ?

+4
1

file-type , ?

npm install --save file-type

var fileType = require('file-type');
var safeTypes = ['image/gif'];
var request = https.request(options, function (response) {
    var chunks = [];
    response.on('data', function (chunk) {
        chunks.push(chunk);
    });

    response.on('end', function () {
        var buffer = Buffer.concat(chunks);
        var file = fileType(buffer) );
        console.log( file );
        //=> { ext: 'gif', mime: 'image/gif' } 

        // mime isn't safe
        if ( safeTypes.indexOf(file.mime) == '-1' ) {
            // do your Base64 thing
        }
    });
});
...
request.end();
...

, Github, .

+1
source

All Articles