01 Project – Node.js / Express / MongoDB – Part 10 – Creating {{ timestamp }} global helper

The global helper that we are going to create will be used to format a timestamp. It will display a date according to how long ago the event occurred. We will use this for things such as comments and image timestamps.

First, we need to update our server/configure.js module. We are going to add a section to define our helpers:

app.engine('handlebars', exphbs.create({
    defaultLayout: 'main',
    layoutsDir: app.get('views') + '/layouts',
    partialsDir: [app.get('views') + '/partials'],
    helpers: {
      timeago: function(timestamp) {
        return moment(timestamp).startOf('minute').fromNow();
      }
    }
  }).engine);

Note:
We added just the helper property, the rest of the code exists in the configure.js file.

We defined the helpers property of the configuration options within create(). Inside the helpers property, we defined the timeago function that uses an npm module called moment . The moment module is a library for performing different types of date string formatting.

Next, we need to require the module at the top of our configure module:

moment = require('moment');

Of course, we have to install it via npm running the following command in the terminal:

$ npm install moment --save

Install moment module

Now, if you check package.json file you can see moment module listed as a dependency.

Leave a Reply