Build Dynamic Blog Using Node.js


Build Dynamic Blog Using Node.js

Recipe ID: hsts-r6


Download source files for this recipe

Description:
This is simple blog for the traveler and story teller.  Easily add and edit authors, create blog posts and assign categories.  Deploy this blog app in minutes to begin documenting your journey.

Learning Objectives

This guide explains:

This study explains how to:

  • Create a simple blog app using node.js with cosmic.js
  • An overview of Cosmic.js
  • You will get the knowledge about modules like express js.

Prerequisites

To complete the steps in this tutorial, you need:

  • Node.js installed locally
  • Make sure you have yarn installed globally
  • You should have understanding of JavaScript & Json

What is Node.js

Node.js is an open source environment that allows JavaScript applications to be run as a server and client at the same time, and so, is very popular for creating and deploying microservices. On an API Connect platform, microservices – in this case Node.js applications – provide the ability to create server endpoints to complete backend service and system of record data requests and serve responses.

Steps

Let’s start by creating a folder for our app. In your favorite terminal run the following commands:

mkdir simple-blog
cd simple-blog

Now let’s add a package.json file to import all of our dependencies for our app:

vim package.json 

Add the following to our package.json file:

{
  "dependencies": {
    "cosmicjs": "^2.39.0",
    "express": "^4.15.2",
    "hogan-express": "^0.5.2",
    "nodemon": "^1.11.0"
  },
  "scripts": {
    "start": "node app.js",
    "development": "nodemon app.js"
  }
}

It’s a pretty light dependency list for a pretty light app. So what we will install is:
1. The Cosmic JS Node Module to get our content from our Cosmic JS Bucket.
2. Express for our web app framework
3. Hogan for our template views
4. Nodemon for development
Our scripts are necessary for starting our app in production and development.
Run the following command to install our dependencies:

yarn 

Building Our Blog

Next, let’s begin building our blog pages. Create a file titled app.js:

vim app.js 

and add the following to app.js:

const express = require('express')
const app = express()
const hogan = require('hogan-express')
const http_module = require('http')
const http = http_module.Server(app)
app.engine('html', hogan)
app.set('port', (process.env.PORT || 3000))
app.use('/', express.static(__dirname + '/public/'))
const Cosmic = require('cosmicjs')
const helpers = require('./helpers')
const bucket_slug = process.env.COSMIC_BUCKET || 'simple-blog-website'
const read_key = process.env.COSMIC_READ_KEY
const partials = {
  header: 'partials/header',
  footer: 'partials/footer'
}
app.use('/', (req, res, next) => {
  res.locals.year = new Date().getFullYear()
  next()
})
// Home
app.get('/', (req, res) => {
  Cosmic.getObjects({ bucket: { slug: bucket_slug, read_key: read_key } }, (err, response) => {
    const cosmic = response
    if (cosmic.objects.type.posts) {
      cosmic.objects.type.posts.forEach(post => {
        const friendly_date = helpers.friendlyDate(new Date(post.created_at))
        post.friendly_date = friendly_date.month + ' ' + friendly_date.date
      })
    } else {
      cosmic.no_posts = true
    }
    res.locals.cosmic = cosmic
    res.render('index.html', { partials })
  })
})
http.listen(app.get('port'), () => {
  console.info('==> 🌎  Go to http://localhost:%s', app.get('port'));
})

There are a few things happening here:
1. We are importing our essential modules: Express, Cosmic JS, setting our PORT dynamically, etc.
2. We are pointing to some partials: header and footer.
3. We view our app home page (‘/’) and query our Cosmic JS Bucket for Post Objects, set the friendly date, then return the index.html template.
4. We are also adding our data to this page in the form of a global data store: cosmic. This data structure makes our template implementation super intuitive.

Adding Our Home Page Template Variables

This part of the process is the most fun because it shows you the power of Cosmic JS combined with a declarative, logic-less template system. Let’s create a folder called views and add our index.html file:

mkdir views
cd views
vim index.html

Add the following to index.html:

{{> header }}
  <main class="container">
    {{# cosmic.objects.type.posts }}
      <div class="card" data-href="/{{ slug }}">
        {{# metadata.hero.imgix_url }}
          <div class="blog-post-hero blog-post-hero--short" style="background-image: url({{ metadata.hero.imgix_url }})"></div>
        {{/ metadata.hero.imgix_url }}
        <div class="card-padding">
          <h2 class="blog__title blog__title--small">
            <a href="/{{ slug }}">{{ title }}</a>
          </h2>
          <div class="blog__author">
            <div class="blog__author-image" style="background-image: url({{ metadata.author.metadata.image.imgix_url }}?w=100)"></div>
            <div class="blog__author-title">by <a href="/author/{{ metadata.author.slug }}">{{ metadata.author.title }}</a> on {{ friendly_date }}</div>
            <div class="clearfix"></div>
          </div>
          <div class="blog__teaser droid">{{{ metadata.teaser }}}</div>
          <div class="blog__read-more">
            <a href="/{{ slug }}">Read more...</a>
          </div>
        </div>
      </div> 
    {{/ cosmic.objects.type.posts }}
  </main>
{{> footer }}

What’s happening here?
1. We pull in our header file with the Mustache template variable.
2. We pull in our Cosmic data using the Mustache variable {{ cosmic }} which has everything we need to layout our page’s dynamic data.
3. We are looping through our {{ cosmic.objects.type.posts }} and rolling out our blog posts.

Conclusion

This is the Simple Blog app. We have made this using Node.js. We have also used the modules like express and cosmic.js.

 

Related Tutorials

Related Training Courses

Advance Website Design Using HTML and CSS
PHP and MySQL Coding
Cross-platform Native App Development Using HTML5, CSS3 and JavaScript
Node.JS Coding with Hands-on Training
Advance JavaScript, jQuery Using JSON and Ajax
jQuery Programming for Beginners
SQL Programming and Database Management
Intro to Dreamweaver with Website Development Training
Adobe Muse Training Course
Introduction to the WordPress CMS
Introduction to the Joomla CMS
Mastering Drupal in 30 Hours
Developing Web Applications Using AngularJS
Introduction to Python Programming
Object Oriented Programming with UML


Private and Custom Tutoring

We provide private tutoring classes online and offline (at our DC site or your preferred location) with custom curriculum for almost all of our classes for $50 per hour online or $75 per hour in DC. Give us a call or submit our private tutoring registration form to discuss your needs.


View Other Classes!