Node-fetch: How do you read binary data?

Created on 16 Aug 2016  路  4Comments  路  Source: node-fetch/node-fetch

It seems a few methods like .blob() are missing to do so

the idea is just making something similar to:

request('some.png', (err, res, body)=>{
    console.log(Buffer.from(body).toString('base64'));
});

Most helpful comment

This is more of a stackoverflow question and not an issue or a bug


you can use res.body which is a stream...
So you can pipe it. Example: res.body.pipe(dest)
or do:

res.body.on('data', chunk => {
   // Got a chunked buffer
}).on('end' () => {
   // end of stream 
})

You now also have the alternativ method to browsers arrayBuffer which is called just buffer (as of v1.6.0) and it will resolve to a node buffer instance res.body.buffer()

fetch('some.png')
.then(res => res.buffer())
.then(console.log)

All 4 comments

This is more of a stackoverflow question and not an issue or a bug


you can use res.body which is a stream...
So you can pipe it. Example: res.body.pipe(dest)
or do:

res.body.on('data', chunk => {
   // Got a chunked buffer
}).on('end' () => {
   // end of stream 
})

You now also have the alternativ method to browsers arrayBuffer which is called just buffer (as of v1.6.0) and it will resolve to a node buffer instance res.body.buffer()

fetch('some.png')
.then(res => res.buffer())
.then(console.log)

Great answer, thanks, sorry

hmm, note with 1.6.0:

fetch('https://small.sdsu.edu/sites/all/themes/zen_larc/widgets/larcrating/smile_small.png')
.then(r=>r.body.buffer())
// .then(r=>r.body.arrayBuffer())
.catch(console.error)

gives me:

TypeError: r.body.arrayBuffer is not a function / TypeError: r.body.buffer is not a function

Yeah as documented in known differences and #51, on Node.js there isn't much point in using arrayBuffer.

This is more of a stackoverflow question and not an issue or a bug

you can use res.body which is a stream...
So you can pipe it. Example: res.body.pipe(dest)
or do:

res.body.on('data', chunk => {
   // Got a chunked buffer
}).on('end' () => {
   // end of stream 
})

You now also have the alternativ method to browsers arrayBuffer which is called just buffer (as of v1.6.0) and it will resolve to a node buffer instance res.body.buffer()

fetch('some.png')
.then(res => res.body.buffer())
.then(console.log)

just use res.buffer(), not res.body.buffer(), as follows:
fetch('some.png')
.then(res => res.buffer())
.then(console.log)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

runarberg picture runarberg  路  5Comments

peterbakonyi05 picture peterbakonyi05  路  6Comments

Janpot picture Janpot  路  4Comments

wheresrhys picture wheresrhys  路  3Comments

normanrz picture normanrz  路  3Comments