I have an image on a web server (http://example.com/img.jpg). I open that image in a browser and save it to disk.
If I open the file in node via the 'fs
' module (fs.readFileSync
), I get a Buffer that begins with 0xff, which is what I would expect.
I'd like to be able to get the same result directly from an HTTP request. I'm using the 'request' module to make the request.
request('http://example.com/img.jpg',function(error, response, body){
//code here
});
I can't figure out how to turn the response or body into an equivalent Buffer from what I'm getting from the FileSystem. What am I missing?
If you are using the HTTP connector, you get a choice of what sort of data format to expect. (See below video). Binary format is used for data which you either do not want to parse, or data which cannot be parsed (such as images and executables). All the other formats are parsable.
Node.js as a File Server To include the File System module, use the require() method: var fs = require('fs'); Common use for the File System module: Read files.
Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method: var http = require('http');
You can get a Buffer
by setting the encoding
to null
:
request('http://example.com/img.jpg', { encoding: null }, function(error, response, body){
console.log(Buffer.isBuffer(body)); // true
});
request
treats any other value as an argument for buffer.toString()
, which defaults undefined
to "utf8"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With