1

I would like to know how I could make my app.js so that I could access any .js or .css file from my index.html or any other html page placed in my "public" folder. I have the .css and .js files placed in different "css" or "javascript" folders inside "public" folder but I dont really know how to make my index.html connect to them without the css and javascript placed directly in the public folder with no subfolders for them to be in.

Is it possible to make it so that all my files in "public" folder can connect without me having to add them into the app.js all the time?

This is the app.js:

var
http = require('http'),
path = require('path'),
fs = require('fs'),

extensions = {
    ".html" : "text/html",
    ".css" : "text/css",
    ".js" : "application/javascript",
    ".png" : "image/png",
    ".gif" : "image/gif",
    ".jpg" : "image/jpeg"
};

function getFile(filePath,res,page404,mimeType){
    fs.exists(filePath,function(exists){
        if(exists){
            fs.readFile(filePath,function(err,contents){
                if(!err){
                    res.writeHead(200,{
                        "Content-type" : mimeType,
                        "Content-Length" : contents.length
                    });
                    res.end(contents);
                } else {
                    console.dir(err);
                };
            });
        } else {
            fs.readFile(page404,function(err,contents){
                if(!err){
                    res.writeHead(404, {'Content-Type': 'text/html'});
                    res.end(contents);
                } else {
                    console.dir(err);
                };
            });
        };
    });
};

function requestHandler(req, res) {
    var
    fileName = path.basename(req.url) || '/index/index.html',
    ext = path.extname(fileName),
    localFolder = __dirname + '/public/',
    page404 = localFolder + '404.html';

    if(!extensions[ext]){
        res.writeHead(404, {'Content-Type': 'text/html'});
        res.end("<html><head></head><body>The requested file type is not supported</body></html>");
    };

    getFile((localFolder + fileName),res,page404,extensions[ext]);
};

http.createServer(requestHandler)

.listen(process.env.PORT, process.env.IP);

Any help would be greatly appreciated and just tell me if you need me to list up my folder structure (though I wouldn't know why that would be neccessary...) :)

3
  • @minitech is right, you should serve your static files out of Nginx. If this is for pure academic reasons, then take a look at other static file server projects like ecstatic or connect static middleware. Commented Jan 16, 2014 at 19:22
  • Are you trying to have CSS and JS files be downloaded and presented in a browser as text? Or just referenced by an HTML page? Commented Jan 16, 2014 at 19:23
  • Just referenced by an html page Daniel Commented Jan 16, 2014 at 19:52

2 Answers 2

2

You can serve up static files using ExpressJS

Sign up to request clarification or add additional context in comments.

1 Comment

Can't recommend using Express enough. If for some reason you really can't use Express, check out the code Express uses under the hood for inspiration. senchalabs.org/connect/static.html. If you need help getting going on Express, I put a screencast together on it. learnallthenodes.com/episodes/…. It'll show you exactly why you want to use Express.
0

Well, you could follow the other advice and use other means to serve your static files, Nginx is probably better suited to straight static file serving, and Express or node-static or any number of modules do a far better job than most of us could throw together at doing the "webserver" part for static files. If you're looking for out-and-out performance, combining node for dynamic + Nginx for static is probably the best combo out there, and pure node using a popular server framework is a slightly simpler, almost as good option.

But here's the actual problem in your code:

var fileName = path.basename(req.url) || '/index/index.html', // etc

path.basename() strips away all directory information, and just returns the filename to you. You want something more like the following:

// you should refactor and expand on this one-liner where it makes sense
var urlpath = require('url').parse(req.url).pathname;
var fileName = urlpath || '/index/index.html', // etc

1 Comment

Oh, and you've opened up your system to a Directory traversal attack, though you've limited it somewhat by white-listing your supported file extensions. Doing this stuff correctly and securely isn't easy, and there are a lot of solid options out there that will do it correctly and securely for you, that's why people will usually suggest you don't do it yourself.

Your Answer

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