Wednesday, November 11, 2015

Creating a Node.js web application from scratch Part 2

This is a continuation of the blog post entry Creating a Node.js web application from scratch Part 1. In that previous article, I told you how to create a simple Node.js application and how to do the routing. Now, let's work more on the front-end.

Step 3 - Add Jade Views

Now, you will add Jade views to your application. Jade is an HTML templating library that helps you create HTML views with minimal effort. First you need to tell our application where to find the Jade views. By convention, Jade templates are created in the views directory. And that's what you tell your application code in app.js.

Next, let's add the index.jade file. Jade is capable of parsing HTML tags. So you can use plain HTML in a Jade file.

This means that you need to tell your routing code in index.js to render index.jade for the root path. 

Next, you need to add the Jade library as a dependency for your app.

Now you can run npm install to install the new dependency, then npm start to start the app and test the result.

Step 4 - Make It Pretty!

Now, it's time to make your app look fancy! You need to tell the application where to find the stylesheets. Stylesheets, Javascript files, static HTML files - i.e. all static content goes in the public directory by convention. So, tell your application to use the /public directory to look for static files.

Next, add the style.css file. This just paints the application background gray.

For kicks, update the Jade file to use actual Jade templating code. As you can see, the link tag is used to include the stylesheet.

Now, restart your application and hit http://localhost:3000 to test out the result.

And there you go! It's gray! And we're using a real Jade template. This is just the beginning. You can do many many things with your application - connect it to the database, create end-to-end use-case flows and what not. But with these blog entries, hopefully you've successfully launched your endeavors!

Happy coding! Cheers! 

No comments:

Post a Comment