I'm trying to learn nodejs and I thought the best way to do this would be to try doing some stuff without using express or any other non-core modules. I'm stuck on trying to get some text and an image to be delivered simultaneously. The code I'm trying is:

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

var server = http.createServer(function(request,response) {

    fs.readFile('my_pic.jpg', function(error, file) {
        response.writeHead(200, {'content-type':'text/html'});
        response.write('<p>hi there!</p>');

        response.writeHead(200, {'content-type':'image/jpg'});
        response.write(file, 'image');

        response.end();
    });

});

var port = process.env.PORT || 8080;

server.listen(port, function() {
    console.log('Listening on port ' + port);
});

So ideally what should be delivered is:

<html>
<body>
<p>hi there</p>
<img src='my_pic.jpg'/>
</body>
</html>

But instead, nothing is appearing.

I tried putting a response.end() after writing 'hi there', which displays the text, and after that I tried swapping the places of the text and picture (headers included), which displayed the picture, but I can't figure out how to get both to display simultaneously, like on a real web page.

Can you explain how to go about putting in different types of content onto the same webpage - do they need to be in different responses? Something I came across on another question:

nodejs - How to read and output jpg image?

Something like that looks like the solution, but I can't figure out how to apply this to my situation (I don't have a lot of experience in the server side of things.)

Many thanks

EDIT: got it working from user568109's reply:

var http = require('http');
va
Edit
Report