jsnoob
jsnoob

Reputation: 965

node.js sending css files

I'm trying to get a node.js server to send css files. I'm modifying this server here:

http://github.com/LearnBoost/Socket.IO-node/blob/master/test/server.js

What's wrong with what I'm doing:

server = http.createServer(function(req, res){
    // your normal server code
    var path = url.parse(req.url).pathname;
    switch (path){
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
            res.end();
            break;

        default:
            if (/\.(js|html|swf)$/.test(path)){
                try {
                    var swf = path.substr(-4) === '.swf';
                    res.writeHead(200, {'Content-Type': swf ? 'application/x-shockwave-flash' : ('text/' + (path.substr(-3) === '.js' ? 'javascript' : 'html'))});
                    res.write(fs.readFileSync(__dirname + path, swf ? 'binary' : 'utf8'), swf ? 'binary' : 'utf8');
                    res.end();
                } catch(e){ 
                    send404(res); 
                }               
                break;
            }
            else if (/\.(css)$/.test(path)){
                    res.writeHead(200, {'Content-Type': 'text/css'});
                    res.end();
                    break;
            }

            send404(res);
            break;
    }
});

Thanks.

Upvotes: 2

Views: 14070

Answers (2)

Marc Bollinger
Marc Bollinger

Reputation: 3119

You're only writing a response header for css requests, for one.

I'd imagine if you call curl -I http://your-server/some-file.css, you'd get back a 200 status with a Content-Length of 0. You could just get away with:

res.write(fs.readFileSync(__dirname + path, 'utf8'));

But a.) Don't Repeat Yourself, and b.) the 'sync' in both of those methods means synchronous. It probably isn't for this version, but in Node in general, you should be just calling readFile and passing a callback to finish the request later on. The API isn't great for directly linking, but the File System section should help, look for 'fs.readFile'.

Upvotes: 4

BC.
BC.

Reputation: 24918

You forgot to send the file.

...
else if (/\.(css)$/.test(path)){
    res.writeHead(200, {'Content-Type': 'text/css'});
    res.write(fs.readFileSync(__dirname + path, 'utf8')); // <--- add this line
    res.end();
    break;
}

Upvotes: 2

Related Questions