Expressing Hello World In MEAN Stack

Ankit Karnany
The Observables
Published in
10 min readSep 19, 2018
“A person's hands crafting pottery on a spinning wheel” by Jared Sluyter on Unsplash

The MEAN stack is an open source JavaScript stack used for building websites. M E A N stands for MongoDB, Express.js, AngularJs and Node.js.

In this article, we’ll unfold some of the most important concepts used in a real world application built upon the MEAN stack.

Let’s get started.

Our goal here is to print Hello World! in the browser when we hit a URL.

Create a file index.html and type:

Hello World!

Open this file in browser and you’ll see Hello World! in the browser. Easy right?

But not so easy. We’ll learn a real world method for achieving the same using Express.js and Node.js by serving the file from a server.

How Node.js Works

Firstly, lets understand what is Node.js. For this, install it first.

Open your browser’s developer console and type console.log("Hello World!"); you’ll get the expected result.

Now, create a file index.js and type:

console.log("Hello World!");

Open your command line and switch to the directory where you created this file. Type node index.js and you’ll see the result similar to what you got on the browser.

Oh Ok! So Node.js acts like a browser?

Basically, it picked up the JavaScript engine from a browser and placed it in our operating system. It is running just like any other software in our operating system with some additional features that a web server might need.

As a web developer, you might have this question:

Which browser? Why a JavaScript engine from the browser? Won’t that bring cross browser compatibility issues?

Excellent! The creators of Node.js had the same questions in their mind before building it. So they picked one of the best browsers out there and ripped it apart. Yes it’s Google Chrome and what they were left with is V8 Engine which runs in its core.

What's so special about V8?

One of the most important things about the V8 Engine is that it follows the ECMAScript Standards, which are also followed by JavaScript.

So we can create a server using JavaScript! That’s good news for Front End Developers. Does it also mean that we can create a server in browser too?

That's an excellent question! But I won’t be answering that. Instead let me shed some more light on how JavaScript works in V8. Then you’ll figure out the answer yourself.

As you probably already know, for any code to run in a computer it needs to be converted into Machine Code. So V8 is basically a compiler which converts JavaScript code into Machine Code, and it’s written in C++. V8 is open source, so if we want to add more functionality in JavaScript we need to add it in the V8.

This is exactly what the Node.js creators did. They modified the V8 Engine by implementing all the necessary features required for a web server.

You might think

That’s all good to hear, but I am still not clear about how can I use it to create a server…

Don’t worry, we’ll get to that.

ES6 In Node.js

Ok, so far we know that Node.js is built using JavaScript, which follows ECMAScript standards — and some pretty cool people keep updating these standards. ES6 was released in 2015, with let , const , () => {} (an easy and fun way to write a function definition), modules , classes , promises…and so on.

The Google peeps behind the V8 are even a little cooler that they are. So, they regularly update the engine with the changes introduced in ECMAScript.

And the people behind Node.js are the coolest among them all, as they keep updating it too.

Most of these features are present in the latest stable release of Node.js. But if we want to use the latest features in the older versions of Node.js, there is a turn around for that. We use a JavaScript compiler called babel on top of Node.js.

For simplicity, we’ll use the Node version 10.5.0 which supports all of the above mentioned features and much more.

Modules In Node.js

We’ll particularly look at one of those features called modules and how it is used in any real world web application built upon Node.js.

We use modules to separate out functionalities in the app. Let’s look at an example.

Suppose you have a file called greetings.js where you keep your Hello World! text:

module.exports = {  hello_world: 'Hello World!'}

Now, change your index.js to:

var greet = require('./greetings');console.log(greet.hello_world);

Again type node index.js and you’ll get the same result as before.

Cool! I can imagine what this feature can help us to achieve in any real world application.

We can organize our code in different modules based on different functionalities without polluting the global scope. Each module will have its own context. The same functionality can be reused throughout the application. This also makes Node.js lightweight because the core modules which are included in the framework are the bare minimum. The core modules which come with Node.js are:

  1. http - Helps us to create a server
  2. url - Allows us to play with the URL
  3. querystring - Deals with query strings
  4. path - Lets us deal with file paths
  5. fs - File I/O
  6. util - Utility functions for developers

Wait! I see a module called http which comes by default with Node.js…This is the one which helps us create server?

Bingo! You are getting the concepts.

Always remember that we are trying to learn how these things are used in a real world application.

HTTP Module In Node.js

Firstly, let us look at how an HTTP module is used.

Change your index.js to:

var greet = require('./greetings'); // Local Modulevar http = require('http'); // Core Modulevar server = http.createServer(function(req, res){  res.write(greet.text);
res.end();
});server.listen(3000);

Run node index.js but you won't see anything now. This time fire up your browser and go to the URL ( localhost:3000) and again you’ll see your plain old Hello World! in the browser.

This is great. But I know in the real world we won’t be using this method. So what’s next?

Whoa! Slow down. Let me show you one more way we don’t use it in real world applications — but is an important piece.

Routing In Node.js

Add another key hello_mars to the greetings.js with text Hello Mars! . It looks like this:

module.exports = {
hello_world: 'Hello World!',
hello_mars: 'Hello Mars!'
}

And change your index.js to:

var greet = require('./greetings');var http = require('http');var server = http.createServer(function (req, res) {  if (req.url == '/') {    res.write(greet.hello_world);
res.end();
} else if (req.url == "/mars") { res.write(greet.hello_mars);
res.end();
} else { res.end('Invalid Request!'); }});server.listen(3000);

Go to localhost:3000 you’ll see your usual Hello World!.

Now, go to localhost:3000/mars .

I figured out the answer. But Eww! this looks super ugly.

Yeah! I know. That’s why we don’t use it in real world applications.

Imagine that we are writing complex db queries, setting response headers or handling authentications. You can only imagine how these features might be implemented, but you cannot imagine how they can be implemented using the above method.

So we want to make these things happen in a web server. Using the http module is just like building a website using vanilla JS.

Express Framework In Node.js

At this point, let me introduce Express.js. It’s a framework build for Node.js which comes bundled with much more than the core http module. It’s actually built upon the http module.

Pros of using Express.js:

  1. Makes the development process easier and faster. It’s clearly evident above how tedious the http modules might get with real world applications.
  2. Allows us to perform additional tasks on request and response using something called Middleware. (Don’t worry it’s really simple and we use it quite often in Node.js. We’ll learn about it later).
  3. Error handling using Middleware.
  4. Serving static files and resources.
  5. Handling routes based on HTTP Methods and URLs.

So we use Express.js just like the HTTP module by importing it using ‘require’?

Correct, but up to a certain point. To make it a little clearer, Express.js a third party module. It does not come included in the core modules of Node.js.

NPM & Package.json

To use Express.js we need to use something called npm (Node Package Manager). No worries. We don’t need to install npm separately. It comes with Node.js. So you already have npm installed in your machine.

Run npm init -y in the directory where you have your index.js & greetings.js .

You’ll see a package.json which got created as a result of the above command. This is the file where we write the name of all the third party modules like Express.js along with the version. So that whenever we need to share this module with a fellow developer, we share the source and package.json. Then they just need to run npm install to download all the third party modules in a directory called node_mudules which are imported using require([Third Party Module]) in the index.js.

This way I don’t need to share all the third party modules which I downloaded when I ran npm install because in real world applications we use a lot of them. It’s not feasible to share the node_modules directory.

There are many other things that package.json allows us to achieve, and we use them a lot in real world applications. Check out this link to know more about the usage of package.json.

OK! It’s time I see some code.

First run npm install express --save. You can check package.json to see that a dependencies object got added:

"dependencies": {
"express": "^4.16.3"
}

Modify the index.js file to:

var greet = require('./greetings'); // Local Modulevar express = require('express'); // Third Party Module
var app = express();
app.get('/', function (req, res) {
res.send(greet.hello_world);
});
app.get('/mars', function (req, res) {
res.send(greet.hello_mars);
});
app.listen(3000);

Run node index.js and test localhost:3000 & localhost:3000/mars in the browser.

Cool! I see the Hello World! and Hello Mars! in the browser, but how is this different than the HTTP module? They look quite similar, and the only difference I see is the way we are handling the URLs.

Great that you are able to figure out the similarities between both the approaches. Yes, the difference we see from the http module way is that we are handling the URL’s separately. And that’s an important feature that we use a lot in real world applications. There are many more features which come with Express.js. If you are curious, check out this link.

Routing In Express.js

Ok, lets see if you understand this:

app.get('/users/:userId/orders/:orderId', function (req, res) {
...
});

It’s easy, right? You are passing the userId and orderId in the URL. But imagine handling this req URL in http module way. The number of if statements we’ll need there to check parameters in the incoming requests. Don’t even try to figure that out.

But in Express.js if you enter localhost:3000/users/1234/orders/56 you can easily get the params from the URL in the req object passed to the callback function. You can check that with console.log in this way:

app.get('/users/:userId/orders/:orderId', function (req, res) {

console.log(req.params); // { "userId": "1234", "orderId": "56" }
});

Check out this link if you want to explore more about routing in Express.js.

Sounds Interesting. So this is how routing is used in a real world application, huhh?

Yes let’s chat about that. And it might get much more complicated than this when there are too many routes to handle.

Middleware In Express.js

Before looking at a real world application, let us first understand Middleware in Node.js.

Middleware is a function which has access to the request object, response object and next function.

Next function? Like neextt function?

Haha! That’s just a convention. You can call it whatever you want.

Before understanding the next function, let’s take a look at the definition of a Middleware function.

function (req, res, next) {  ...}

Now, to understand the next function, suppose we have two Middleware functions like this:

function (req, res, next) {  // do something with the req  next();}function (req, res) {  res.send("Hello World!");}

The order of the Middleware functions is important. If we place the first function after the function with res.send(), then it won’t come into that function.

Imagine that an HTTP call comes to your Node.js server. It comes to the first Middleware function. The request object is modified little bit and the next function is called. Then it comes to the next Middleware function. Here a response is sent, thus closing the HTTP call.

Let’s look at how we use this in a real world application.

Modify your index.js file to add a Middleware:

var greet = require('./greetings');var express = require('express');
var app = express();
var log = function(req, res, next){ // Declaring a function
console.log('Inside Server!');
next();
}
app.use(log); // Express.js provides use method which registers
// this middleware to be used when a request
// comes to the server.
app.get('/', function (req, res) {
res.send(greet.hello_world);
});
app.get('/mars', function (req, res) {
res.send(greet.hello_mars);
});
app.listen(3000, function () {
console.log("Listening to port 3000!");
});

Now run node index.js and go to localhost:3000 . You’ll see the text Inside Server! in the server log in the command line and Hello World! in the browser.

You’ll see a similar behaviour when you hit localhost:3000/mars .

Now, let’s move the line app.use(log) between the two get methods and repeat the above.

var greet = require('./greetings');var express = require('express');
var app = express();
var log = function(req, res, next){ // Declaring a function
console.log('Inside Server!');
next();
}
app.get('/', function (req, res) {
res.send(greet.hello_world);
});
app.use(log);app.get('/mars', function (req, res) {
res.send(greet.hello_mars);
});
app.listen(3000, function () {
console.log("Listening to port 3000!");
});

We see the text Inside Server! only when we hit localhost:3000/mars . So the order in which Middlewares are declared is super important.

So, Middlewares are functions which can change the request and response of an incoming HTTP call. And we can have as many Middlewares as we want in between. Am I Correct?

Bingo! You’ve got it.

Real World Application

So now you can easily understand a real world application.

var express = require('express');
var app = express();
// Third party modules
var cookieParser = require('cookie-parser');
var cors = require('cors');
// Local modules created for this project
var userAuthentication = require('./config/auth');
var userController = require('./controllers/users');
var user = require('./models/users');
// a middleware to resolve incoming
// requests coming in json format
app.use(express.json());
// a middleware to resolve incoming
// requests coming in url encoded format
app.use(express.urlencoded({ extended: false }));
// a middleware to handle the cookie
// in request or response object
app.use(cookieParser());
// a middleware to enable cross origin resource sharing
app.use(cors());
// we can pass an array of middlewares to a route
// all the middlewares are resolved in the same sequence
// #1 a middleware to authenticate the incoming user
// #2 a middleware to get the user details from db
// #3 a middleware to send the user details in a proper format
app.get('/getUserDetails', [
userAuthentication,
// 1
userController.getUser,
// 2
user.sendResponse
// 3
]);
app.listen(3000, function () {
console.log("Listening to port 3000!");
});

Wooh! That’s real world?

Yup. This is a snippet.

Thanks for reading! I hope you learned something.

--

--