Monday, 24 April 2017

Can't get image from filesystem module with NodeJS

I created a http server and I'm trying to dispay an html page which is requesting an image with the filesystem module. The image is not getting loaded. I'm not sure if request.method=='GET' is the right way to handle this kind of request.

this is my js code

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

var server = new http.Server();
server.listen(8080);

server.on("connect",function(){
    console.log("New connection success");
});

server.on("close",function(){
    console.log("Connection closed");
});

server.on("request",function(request,response){
console.log("New request");

response.writeHead(200, {"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);

if(request.method == 'GET'){
    console.log("Getting image")
    response.writeHead(200, {"Content-Type":"image/x-icon"});
    var input = fs.createReadStream("./image.jpg");

    input.on("data",function(data){
             response.write(data);
    });

    input.on("end",function(){
        response.end();
    });
}
});

and I'm trying to load this html page:

<html>
    <head>
    </head>
          <body>
             <h1>Immagine</h1>
             <img src='?getImage' style='width:200px'>
          </body>
</html>



via sguci

No comments:

Post a Comment