Getting binary content in node.js with http.request

后端 未结 7 1477
广开言路
广开言路 2020-12-02 16:50

I would like to retrieve binary data from an https request.

I found a similar question that uses the request method, Getting binary content in Node

7条回答
  •  执念已碎
    2020-12-02 17:26

    Running on NodeJS 6.10(and 8.10, tested in Feb 2019) in the AWS Lambda environment, none of the solutions above worker for me.

    What did work for me was the following:

    https.get(opt, (res) => {
        res.setEncoding('binary');
        let chunks = [];
    
        res.on('data', (chunk) => {
            chunks.push(Buffer.from(chunk, 'binary'));
        });
    
        res.on('end', () => {
            let binary = Buffer.concat(chunks);
            // binary is now a Buffer that can be used as Uint8Array or as
            // any other TypedArray for data processing in NodeJS or 
            // passed on via the Buffer to something else.
        });
    });
    

    Take note the res.setEncoding('binary'); and Buffer.from(chunk, 'binary') lines. One sets the response encoding and the other creates a Buffer object from the string provided in the encoding specified previously.

提交回复
热议问题