To read and output jpg image with Node, we read it with readFile
.
For instance, we write
const http = require("http");
const fs = require("fs");
fs.readFile("image.jpg", (err, data) => {
if (err) {
throw err;
}
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "image/jpeg" });
res.end(data);
})
.listen(8080);
});
to call readFile
to read the image.jpg file.
And then we call createServer
with a callback that calls res.end
with the read data
to return that as the response.
We call writeHead
to write the Content-Type
header with the MIME type as its value.