DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Update to my Node Blog Engine

Raymond Camden user avatar by
Raymond Camden
·
Sep. 11, 12 · Interview
Like (0)
Save
Tweet
Share
4.43K Views

Join the DZone community and get the full member experience.

Join For Free

Just a quick Sunday post (mainly so I can avoid stressing over my Saints). A week or so I posted about my first attempt to build a "real" Node.js app with Express. My goal was to build a simple front end to my blog database. This gave me a simple enough application to learn Node/Express as well as plenty of data. I've been able to update the application quite a bit and I thought I'd share what I've done. As before, please do not consider this best pratice Node.js/Express development. I'm still very early in my Node education.

One of the first changes I've been able to make is with my view engine. I mentioned in the previous blog post how I wasn't a fan of the syntax that EJS used. As a reminder, here is what it looks like:

<h2>Blog</h2>

<ul>
<%
    entries.forEach(function(entry) {
        var d = new Date(entry.posted);
        var year = d.getFullYear();
        var month = d.getMonth()+1;
        var day = d.getDate();
%>
    <li><a href="/<%= year + '/' + month + '/' + day %>/<%= entry.alias %>"><%= entry.title %></a> (<%= entry.posted %>)</li>
<% }) %>
</ul>

I was able to switch my view engine to one that made use of Handlebars. The node package hbs allows you to use you Handlebars in your HTML templates. So the above becomes something a bit nicer:

<h2>Blog</h2>

<ul>
{{#each entries}}
    <li><a href="{{bloglink this.posted this.alias}}">{{this.title}}</a> ({{this.posted}})</li>
{{/each}}
</ul>

To be fair to EJS, I also added a helper function "bloglink" to simplify the creation of the SES-style link. To make my application even more stylish (heh), I added a layout.html to my views page. This automatically wraps my views:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="/static/styles.css" />
    <title>{{title}}</title>
</head>

<body>

<header>Ray's Blog</header>

{{{body}}}

<p>
<a href="/">Home</a>
</p>

</body>
</html>

Obviously that isn't a full template, but it gives you a basic idea. Two things I want to call out here. Three things actually.

First, note the use of {{{body}}}. This is where the previously rendered view will be inserted.

Second, note the use of {{title}} on top. As long as I set a title value when rendering my view, this will be picked up and used, so for example, check out the code that renders a blog entry:

app.get("/:year/:month/:day/:alias", function(req, res) {
    var entryDate = new Date(req.params.year,req.params.month-1,req.params.day);
    blog.getBlogEntry(entryDate,req.params.alias,function(entry,comments) {
        res.render("entry", {entry:entry,comments:comments,title:entry.title});
    },function() {
        res.writeHead(302, {
            'Location': '/'
        });
        res.end();
    });
});

See the third argument passed to render? That's where I supported a dynamic title for a blog entry.

Finally - note the CSS link. Don't forget Express makes it easy to set up a folder of static stuff your application can use. Things like CSS files and JavaScript libraries. Here's how I did it:

app.use('/static', express.static(__dirname + "/public",{maxAge:86400000}));

So to me - being able to use Handlebars is huge. I'm a lot more comfortable with it than EJS and I found myself being a lot more productive as I built out the application. Excitement is a good thing, I think.

I made a few more changes that I want to share. As I mentioned in my previous post, app.js is the core application file for your Node.js file. It certainly isn't your only file, but it's the critical top level commander of everything your site does. With that being said, I have this feeling that I should keep things as clean as possible.

As an example, I built a utility library that would let me define Handlebars helpers (think formatting functions). This kept my app.js a bit cleaner. Here is the current version of it with a grand total of one helper now. I'll add more later.

getHelpers = function() {

var helpers = [];

helpers.push({name:"bloglink", helper:function(date, alias) {
var d = new Date(date);
var year = d.getFullYear();
var month = d.getMonth()+1;
var day = d.getDate();
return '/'+ year + '/' + month + '/' + day +'/'+ alias;
}});

return helpers;
};

exports.addHelpers = function(hb) {
var helpers = getHelpers();
for(var i=0, len=helpers.length; i<len; i++) {
hb.registerHelper(helpers[i].name, helpers[i].helper);
}
return hb;
};

My app.js then can be a bit simpler:

var hbs = require('hbs');
//loads in a library of helpers and adds them to hbs
var helpers = require('./helpers.js');
hbs = helpers.addHelpers(hbs);

Finally, I also removed the custom RSS code from app.js. I moved it into my blog library instead. This is how it looks in app.js (and it's a good 1/5th the size):

app.get("/blog.rss", function(req, res) {

    blog.getRSS(function(xml) {
        res.writeHead(200, {'Content-Type':'application/rss+xml'});
        res.write(xml);
        res.end();
    });

});

For folks who want to see the complete code base, I've attached it below. Obviously you need data, and if anyone wants some sample data from my blog, just ask.

Download attached file

Blog Engine application

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Best Practices for Writing Clean and Maintainable Code
  • The Real Democratization of AI, and Why It Has to Be Closely Monitored
  • Implementing Adaptive Concurrency Limits
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: