Travis Finlan
Travis Finlan

Reputation: 45

How do I load an image on a node.js server?

I want to load an image on a node.js file. But, when i try to fs.readfile, it errors out if there is no image file there after the server is running. But, when i start my server, the image gets downloaded and displays and works correctly.

When i keep the server running and delete the image and try to refresh the page, hoping the image will be redownloaded and display still, it errors out on the fs.readfile because the image file isnt there because it does not redownload if it is deleted.

How do i go about making the webpage dynamic so when i refresh localhost:1337, the image gets downloaded everytime, instead of just when the server is started?

Here is my code so far.

//Dilbert Comic Server
var http         = require('http'),
    fs           = require('fs'),
    request      = require('request'),
    url          = require('url'),
    cheerio      = require('cheerio'),
    request      = require('request'),
    DilbertURL   = 'http://Dilbert.com/strip/' + getDateTime();

http.createServer(function (req, res)
{
       var img = fs.readFileSync('./Dilbert.jpg');
       res.writeHead(200, {'Content-Type': 'image/gif' });
       res.end(img, 'binary');
      console.log('Server running at http://127.0.0.1:1337/');
}).listen(1337, '127.0.0.1');

request(DilbertURL, function (error, response, body) {
    var $ = cheerio.load(body);
    $('div.container-fluid').each(function(i, element){
      var src = $('.img-responsive.img-comic').attr("src");

      download(src, 'Dilbert.jpg', function()
      {
        console.log('Image downloaded');
      });
    });
});

var download = function(uri, filename, callback){
    request.head(uri, function(err, res, body){
      console.log('content-type:', res.headers['content-type']);
      request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
    });
};

function getDateTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + "-" + month + "-" + day ;
}

I am very new to Node.js, so bear with me please.

Upvotes: 2

Views: 10986

Answers (1)

Arm1stice
Arm1stice

Reputation: 101

The problem with your code right now is that you are downloading the picture in what is known as the global scope, so when Node.JS loads the file and reads all the code, it sees that function and will run it just one time. To do what you would like to accomplish (have the server download the picture every time) you have to put the download function inside of the function that executes when the web server receives a request, like so:

//Dilbert Comic Server
var http = require('http'),
  fs = require('fs'),
  request = require('request'),
  url = require('url'),
  cheerio = require('cheerio'),
  DilbertURL = 'http://dilbert.com/strip/' + getDateTime();

 http.createServer(function(req, res) {

   request(DilbertURL, function(error, response, body) {
    var $ = cheerio.load(body);
    $('div.container-fluid').each(function(i, element) {
      var src = $('.img-responsive.img-comic').attr("src");

      download(src, 'Dilbert.jpg', function() {
        var img = fs.readFileSync('./Dilbert.jpg');
        res.writeHead(200, {
          'Content-Type': 'image/gif'
        });
        res.end(img, 'binary');
      });
    });
  });

}).listen(1337, '127.0.0.1', function(err){
  if(err){
    console.log("Failed to start web server:", err);
  }else{
    console.log('Server running at http://127.0.0.1:1337/');
  }
});

var download = function(uri, filename, callback) {
  request.head(uri, function(err, res, body) {
    console.log('content-type:', res.headers['content-type']);
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};
function getDateTime() {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  month = (month < 10 ? "0" : "") + month;
  var day  = date.getDate();
  day = (day < 10 ? "0" : "") + day;
  return year + "-" + month + "-" + day ;
}

NOTE: I cleaned up your code a little by performing the following fixes: 1) You were setting the request variable twice, so I removed the second one. 2) You were printing out the 'Server running..' string every time the server got a request, so I made it print out when the server started without an error.

Welcome to Node.JS!

Upvotes: 3

Related Questions