Add a public directory to express

By convention, images, javascript and css files are stored in a public directory in express. Create a public directory in the root of your project and add 3 directories to it

  • images
  • javascript
  • stylesheets

You can rename the directories, but as the names are commonly used it's better to stick to it.

project_structure_express.pngIn the image on the left my project structure is shown. To see the content of the files and the way it is build, you can read the article create a basic express application.

Now, create a script.js file in the javascript directory and a style.css file in the stylesheets directory. You can also add an image to the images directory. In this example I want to show the Dribbit logo so I added a dribbit_logo.png file.

We need to add some code inside the script.js file to see it in action.


window.onload = function() {
    console.log('Window loaded');
};

And also some style rules in the css file.


body {
    color: red;
}

We can now add the image, javascript and style sheet to the index.jade file. In the end, this has the same behaviour as loading them into a usual .html file.


html
    head
        title Index page using Jade
        link(rel="stylesheet", href="stylesheets/style.css")
    body 
        h1 Front page
        img(src="images/dribbit_logo.png")
        script(src="javascript/script.js")

However, when starting the application by typing "node app.js" in the terminal, the path to the files isn't right. This is because express doesn't know about the pubkic directory. We need to tell express about the public directory, which can be done by adding the directory as a static directory to the application.


/* 
 * @author: Dribbit
 * 
 */

// Load http module.
var http = require('http');
// Load express module.
var express = require('express');

// Initialize app object.
var app = new express();

// Use app.set to add the view engine.
// Ass app is an express object, it has a view engine property.
app.set('view engine', 'jade');
 
// Set path to views.
app.set('views', './views');

// Let express know there's a public directory.
app.use(express.static('./public'));

// Basic routing.
app.get('/', function(req, res) {
    // res.send is changed to result.render in order to load the correct view.
    res.render('index');
});

// Create server and listen on port 3030.
http.createServer(app).listen(3030, function() {
    console.log('Server running...');
});

As you can see in the image below, we now have a front page and are ready to build and design the application.

front_page.png

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.