58

I've been trying to find an example of how to read a jpeg image and then show the image.

var http = require("http"), fs = require("fs");

http.createServer(function (req, res) {
    res.writeHead(
      200, 
      { "Content-Type": "text/html" }
    );

    fs.readFile("image.jpg", function (err, data) {
      if (err) throw err;
      res.write(data);
    });

    res.end();
}).listen(8124, "127.0.0.1");

console.log("Server running at http://127.0.0.1:8124/");

Tried the following code but I think the encoding needs to be set as buffer. Using console.log it outputs 'Object' for the data.

2 Answers 2

104

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to do it so lets say we read the jpeg data and put in the src attribute maybe through encoding it to base64?
Awesome! Just the solution I needed. Thanks for that second example.
what about if we have multiple images ?
1

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.