0

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.

4
  • 1
    What's your environment like? Mac or Windows?
    – TriniBoy
    Commented Apr 18, 2014 at 15:55
  • Hi Triniboy, i'm on Mac Commented Apr 18, 2014 at 15:56
  • OK and are your assets actually sitting in the location specified? Is the log file giving any errors?
    – TriniBoy
    Commented Apr 18, 2014 at 16:04
  • The problem is from the localhost and node.js but i didn't know how to solve it and there isn't other errors. Did you ever use node.js? Commented Apr 18, 2014 at 16:14

3 Answers 3

2

You're doing way more than necessary. Using express, you can set static routes via middleware that will serve content from a set path:

app.use('/js', express.static(__dirname, + '/js')));
app.use('/css', express.static(__dirname, + '/css')));

You can read more about that here: http://expressjs.com/faq.html#multiple-statics

6
  • Ok thanks, but i'm totally inexperienced. Where should i put it? I'm trying but ReferenceError: express is not defined Commented Apr 18, 2014 at 16:52
  • I really don't get it. So, i must delete all the imtesting var and put these two lines where? Commented Apr 18, 2014 at 17:59
  • If you're using imtesting to serve static files, you don't need that function at all. Read up more on how to set middleware: expressjs.com/4x/api.html#app.use. A few paragraphs down it goes into more details about the built in static middleware.
    – scurker
    Commented Apr 18, 2014 at 18:32
  • Still doesn't work with these two lines, don't know why Commented Apr 18, 2014 at 20:27
  • app.use(express.static(path.join(__dirname, 'public'))); work well! Thanks for the help guys Commented Apr 18, 2014 at 20:44
0
app.use(express.static(path.join(__dirname, 'public')));
0

why using other frameworks when it is too easy using raw node.js

take a look :

<!DOCTYPE HTML>
<html>

<head>
    <link rel="stylesheet" href="css/style.css" />
</head>

</html>

**in node.js file : **

var url = require('url');
var pathnaame = url.parse(req.url,true)
var filepath = "./"

if(fs.existsSync(filepath+pathname)){
        res.end(fs.readFileSync(filepath+pathname));
    }

browsers send get requests to fetch css/js files; **in this case : ** it will result like

pathname="css/style.css"
filepath = "./"
filepath + pathname = "./css/style/css"

fs.readFileSync will return true and serve the data to response.

you can also do this in asynchronous way using asynchronous functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.