Write a post

Get Started with Meteor by Building a Chat App

Published Aug 31, 2015Last updated Jan 18, 2017
Get Started with Meteor by Building a Chat App

Introduction

MeteorJS is awesome framework built for developing real-time web apps. Meteor lets developers focus on their application and forget about facing complexity when developing real-time apps (e.g. apps that need to sync and immediately update data to all users).

In this tutorial we will:

  • Download and configure Meteor.
  • Go through the main features of Meteor
  • Run the sample app
  • Understand Meteor's folder structure.
  • Develop a simple chat application.

You can download sample code here.

Downloading and Configuring Meteor

Go to the official Meteor site and download the application. Windows users can follow the installation wizard to install it.

Mac and Linux users can run the following command to install it directly into your machine:

curl https://install.meteor.com/ | sh 

enter image description here

Once you've installed Meteor, run the following command to access meteor through the command line.

meteor

Features of Meteor

1 : Full-stack JavaScript.
Meteor uses JavaScript as its implementation language for its frontend, back-end, and database. In terms of UI, it uses its own templating system. The backend is written on Node.js and uses MongoDB as database software, which in turn works on JavaScript data format.

2 : Full reactiveness.
This is where Meteor gets interesting. If you have developed a real-time web app such as a chat application, then you might know how difficult it is to maintain the reactiveness feature (e.g. if one node made some changes, others should be informed and updated immediately).

Well, not any more. MeteorJS is making it very easy for us to support a reactive feature. All you need to do is build a web app and it will be fully reactive across all connected users.

3 : Cross platform.
Whatever web app you develop using Meteor can be successfully converted to an Android or iOS mobile app using a simple command. Meteor will manage your port view and screen visibility.

Runing a Sample App

First, let's run the following command.

meteor create myFirstApp

It will create folder named myFirstApp and create source files in it. Switch to this directory and run following command.

meteor

Visit localhost:3000 to view the app.

Understanding the Meteor folder structure.

/client - stores all code that runs on client here

/server - where the logic which runs on the server should go

/public - put all static files over here.

This way, you don’t need to provide the entry point of program, as Meteor will find and run the appropriate code.

You can even put the code in same file of Client and Server.

if (Meteor.isClient) {
  // code here will only be run on the client
}

if (Meteor.isServer) {
  // code here will only be run on the server
}

Developing a Simple Chat App

Let’s first create our app.

meteor create chatApp

This will create the default files, but we don’t need them so delete those files.

rm -rf *

Now let’s create the client folder.

mkdir client

We will place our client side code in this directory.

Before moving ahead, we need to create a MongoDB collection. If we create a file named models.js, Meteor will access it as the database file. Inside we will create the new Mongo collection.

You may wonder where are we creating MongoDB database ? We are not. Meteor does create database for your application automatically as soon as your create new Meteor app.

/**
* Create new collection if not present.
*/
Messages = new Meteor.Collection('messages');

Inside the client, let’s create three files named as client.html, client.css and client.js.

Here is the client.html.

<html>
<head>
  <title>Meteor Chat Application.</title>
</head>

<body>  
  <h1>Chatapp</h1>
  {{> welcome }}
  {{> input }}
  {{> messages }}
</body>

<template name="welcome">
  <p>
    Let's chat.
  </p>
</template>

<template name="messages">
  {{#each messages}}
    <strong>{{name}}:</strong> {{message}}<br>
  {{/each}}
</template>

<template name="input">
  <p>Message: <input type="text" id="message"></p>
</template>
</html>

As you can see inside body section, we defined these :

{{> welcome }}
{{> input }}
{{> messages }}

These are template names, and each name will be replaced by the code in the template block (which we did in the same file), so when you run the HTML file >welcome, you'll get :

<p>
  Let's chat.
</p>

And same goes for the other template names.

Template messages will show the chat messages entered by the user, and this will be fetched from MongoDB in our JS file which I'll explain as below.

We will loop over the MongoDB returned messages and replace {{name}} and {{messages}} helpers with the appropriate data.

In Meteor, each template gets "helpers", which in simpler term is like a two-way binding variable.

Here is our client.css:

html {
  padding: 10px;
  font-family: Verdana, sans-serif;
}

.login-buttons-dropdown-align-right {
  float: right;
}

Here is our most important file: client.js

/**
* Templates
*/
if (Meteor.isClient) {
  Template.messages.helpers({
    messages: function() {
    return Messages.find({}, { sort: { time: -1}});
  }
  });

  Template.input.events = {
    'keydown input#message' : function (event) {
    if (event.which == 13) { // 13 is the enter key event
      if (Meteor.user())
      var name = Meteor.user().profile.name;
        else
      var name = 'Anonymous';
        var message = document.getElementById('message');
        if (message.value != '') {
      Messages.insert({
        name: name,
      message: message.value,
      time: Date.now(),
          });

          document.getElementById('message').value = '';
          message.value = '';
        }
      }
    }
  }
}

First we are checking if this is a client or server. If it's a server, we'll first fetch messages from MongoDB and publish them to the message template.

So, when you run the app after closing it, you can see your old chat messages stored in MongoDB. find({}) will fetch all records from the particular collection of MongoDB and return it back.

Here we are returning all messages from MongoDB to our template messages where we are looping over the records cause it will be array of JSON and printing two keys which is name and message.

In order to delete old data from MongoDB and reset the application, just run the following command:

meteor reset

Now, on the Enter key event at the selection of text box, we are fetching the message form textbox and pushing it into MongoDB using standard insert() function.

Messages is the name of the collection defined in models.js. You may notice we are fetching and storing data in pure JSON format.

Running the Chat App

Go to project folder and run following command:

meteor

You should see following in your console:
enter image description here

Now go to localhost:3000 using two browser windows using different profiles.

enter image description here

You can see live updates in both windows.

Final words

Meteor implements mini Mongo in your browser for quick debugging so that you can access data in your browser only.

To get one single row from the database, run the following command in your browser terminal:

Messages._collection.findOne()

The result:
enter image description here

However, you should remove this feature before pushing it to production. Do this using following command:

meteor remove autopublish

This will make sure no one will have access to your MongoDB database from their browser. Finally, you can deploy the app to Meteor's site using

meteor deploy youraccount.meteor.com

Conclusion

So we have learned how to configure and build a sample Meteor app. I hope this is good start for you. Stay tuned for more awesome articles like this.

Discover and read more posts from Shahid Shaikh
get started
Enjoy this post?

Leave a like and comment for Shahid

Application Design in Ember.js
A to Z List of Useful Node.js Modules
Fast and Efficient Pagination in MongoDB