Question

I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!

var http = require('http'),  
    io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io') 

server = http.createServer(function(req, res){ 
 // your normal server code 
 res.writeHead(200, {'Content-Type': 'text/html'}); 
 res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>'); 
});
server.listen(8080);

// socket.io 
var socket = io.listen(server); 
Was it helpful?

Solution

For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.

You may add some code to your function like:

var http = require('http'),  
    io = require('socket.io'),
    fs = require('fs'),
    server = http.createServer(function(req, res){ 
        // find static image file
        if (/\.gif$/.test(req.pathname)) {
            fs.read(req.pathname, function(err, data) {
                res.writeHead(200, { 'Content-Type': 'image/gif' });
                res.end(data);
            });
        }
        else {
            // write your div
        }
    });
server.listen(8080);

I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top