i'm discovering Node.js and i get a little problem with my .css and .js files in localhost. I tried a lot of things but didn't work in my case (http://ericsowell.com/blog/2011/5/6/serving-static-files-from-node-js by exemple)
My files are like this:
mysite/app.js
mysite/index.html
mysite/package.json
mysite/css/ my .css files
mysite/js/ my .js files
mysite/node_modules/ all node.js modules
I tried this in app.js:
var app = require('express')(),
http = require('http');
fs = require('fs');
path = require('path');
imtesting = function (req, res) {
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.htm';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}
server = http.createServer(app, imtesting),
io = require('socket.io').listen(server),
ent = require('ent'), // Permet de bloquer les caractères HTML (sécurité équivalente à htmlentities en PHP)
// Chargement de la page index.html
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket, pseudo) {
// Dès qu'on nous donne un pseudo, on le stocke en variable de session et on informe les autres personnes
socket.on('nouveau_client', function(pseudo) {
pseudo = ent.encode(pseudo);
socket.set('pseudo', pseudo);
socket.broadcast.emit('nouveau_client', pseudo);
});
// Dès qu'on reçoit un message, on récupère le pseudo de son auteur et on le transmet aux autres personnes
socket.on('message', function (message) {
socket.get('pseudo', function (error, pseudo) {
message = ent.encode(message);
socket.broadcast.emit('message', {pseudo: pseudo, message: message});
});
});
});
server.listen(8080);
But the result is still
GET http://localhost:8080/css/bootstrap.min.css 404 (Not Found) localhost/:14
GET http://localhost:8080/css/site-style.css 404 (Not Found) localhost/:17
GET http://localhost:8080/css/spray-style.css 404 (Not Found) localhost/:21
GET http://localhost:8080/js/bootstrap.min.js 404 (Not Found) localhost/:98
GET http://localhost:8080/js/spray-reader.js 404 (Not Found) localhost/:99
and i tried a lot of solutions...
Thanks all and sorry if my english made your eyes bleeding.