oopsi
oopsi

Reputation: 2019

Node js. sending an html that contains an image

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");

Upvotes: 3

Views: 4022

Answers (2)

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

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.

Upvotes: 6

trebuchet
trebuchet

Reputation: 1481

The issue is that node isn't aware of your image and can't serve static files out-of-the-box like your average web server. Using a framework like express makes this much easier.

Upvotes: 4

Related Questions