Categories
JavaScript Answers

How to read and output jpg image with Node?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *