Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js. sending an html that contains an image

Tags:

html

node.js

I have built a simple server using node js. I wish to send an html that contains an image inside.

Ok, so i know how to send back an html file. And i know how to send back an image.

When i send the html response with the <img src = 'green2.jpg'> in it, the page loads with a broken image.

Any ideas?

Relevant code :

var net = require ('net');
var url = require('url');
var fs = require('fs');

var server = net.createServer(function (socket) {
    socket.on('end', function() {
        console.log('server disconnected');
    });

    socket.on('data', function(data) {
        get();
    });

    var get = function (parse) {
        fs.readFile('example.html',  function(err, data) {
            if (err) throw err;
            socket.write('HTTP/1.0 200 OK\r\nDate: Fri, 31 Dec 1999 23:59:59 GMT\r\nContent-Type: text/html\r\n\r\n');
            socket.write(data);
            socket.end();
        });
    }
});

server.listen("8888");
like image 837
oopsi Avatar asked Dec 21 '25 05:12

oopsi


1 Answers

Your current code is saying this:

Anytime I get any request, send down the contents of example.html.

If someone asks for /whatever.jpg they're going to get the contents of example.html which of course will show you a broken image.

If you want to server up static files using node.js you'll want to probably use something like Express.js which handles it automatically using the express.static middleware referenced here: http://expressjs.com/api.html#app.use

Obviously "use express" isn't an answer to your question, but the answer to your question using pure node.js is either one of the following:

  1. Install a module like node-static to handle static files like images. Tutorial here
  2. Use a switch statement on req.url to figure our which file the server is looking for and send it down using something similar to your fs.readFile('example.html'), but that could also read an image file.
like image 142
Jamund Ferguson Avatar answered Dec 22 '25 21:12

Jamund Ferguson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!