title: Image with socket io node js
body: <p>I am trying to do something that sounds quite simple but unfortunately I can't manage to get right.</p>
  
  <p>I just need to stream an image from a file with socket.io.</p>
  
  <p>I have read several links that were either outdated or incomplete and here is where I am right now (not working) : </p>
  
  <p>server.js</p>
  
  <pre><code>var app = require('express')();
  var http = require('http').Server(app);
  var io = require('socket.io')(http);
  var bodyParser = require('body-parser');
  var fs = require('fs');
  
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended:false}));
  
  app.get('/',function (req,res){res.sendStatus(200)});
  app.get('/image',function (req,res){res.sendFile(__dirname+'/index.html')});
  
  
  http.listen(3000, function () {
      console.log("server listening");
  }); 
  
  io.on('connection',function(socket){
      console.log("socket connection");
      var interval = setInterval(function(){
          fs.readFile('./image.jpeg',function(err,buff){
              if(err){
                  console.error(err);
              }
              else{
                  socket.emit('image',{image:true,buffer:buff.toString('base64')});
              }
          });
      },1000);
      socket.on('disconnect', function(){
          console.log("socket deconnection");
          clearInterval(interval);
      });
  });
  </code></pre>
  
  <p>index.html</p>
  
  <pre><code>&lt;html&gt;
    &lt;head&gt;
      &lt;meta charset="UTF-8"&gt;
      &lt;title&gt;IMAGE&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
      &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
      &lt;script&gt;
        $(function(){
          var socket = io();
          var ctx = document.getElementById('canvas').getContext('2d');
          socket.on('image',function(info){
            if(info.image){
              var img = new Image();
              img.onload = function () {
                ctx.drawImage(img, 0, 0);
              };
              img.src = 'data:image/jpeg;base64,' + info.buffer;
              console.log("Image received");
            }
          })
        });
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>I have also tried several other configurations close to this one for the client file but none of them worked.</p>
  
  <p>I read the file at interval because in the real project the image.jpeg file will change at times.</p>
  
  <p>Thank you very much if you can help !</p>