Robust Codes

Build a NodeJS Application with ES6 modules

March 22, 2020

In these series of tutorials, we are going to build a web application from the ground up using NodeJS and Express

I’m using node:13.10 which has support of ECMAScript modules without a flag

Let’s set up our first page.

We create a new directory called hello_nodejs

root@e47199b3c130:/# mkdir hello_nodejs
root@e47199b3c130:/# cd hello_nodejs/

We initialize our project by open a terminal and type npm init

root@e47199b3c130:/hello_nodejs# npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (hello_nodejs)
version: (1.0.0)
description: NodeJS-ExpressJS Application with ECMAscript modules
entry point: (index.js)
test command:
git repository: https://github.com/alexkantas
keywords: nodejs express es_modules
author: Alex Kantas
license: (ISC) MIT
About to write to /hello_nodejs/package.json:

{
  "name": "hello_nodejs",
  "version": "1.0.0",
  "description": "NodeJS-ExpressJS Application with ECMAscript modules",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/alexkantas"
  },
  "keywords": [
    "nodejs",
    "express",
    "es_modules"
  ],
  "author": "Alex Kantas",
  "license": "MIT"
}


Is this OK? (yes) y

We can use npm init -y to skip the questionnaire

A package.json file is added to our directory

root@e47199b3c130:/hello_nodejs# ls
package.json

We are going to use ECMAScript modules

 import someModule from 'SomeModule'

insted of commonJS modules

const someModule = require('SomeModule')

so we need to add "type":"module" in our package.json

Now we have to install Express

npm install express --save 

or shorter

 npm i express -S 

This command install express with its dependencies in node_modules directory and the -S option added as dependency in package.json

Every dependency that express needs added to package-lock.json

Our package.json file now looks like this

{
  "name": "es_modules_node",
  "version": "1.0.0",
  "description": "NodeJS-ExpressJS Application with ECMAscript modules",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/alexkantas"
  },
  "keywords": [
    "nodejs",
    "express",
    "es_modules"
  ],
  "author": "Alex Kantas",
  "license": "MIT",
  "type": "module",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Every dependency need it to be on package.json so when we run

npm install

all listed dependencies downloaded and added to node_modules folder

That’s very useful since we don’t have to add node_modules folder when need to share our project or upload it to an external repository

Let’s add our first file index.js

import express from 'express'

var app = express();
var port = 80;

app.get('/', function (req, res) { res.send('Hi!') })

app.listen(port, function () { console.log('Server listening on ' + port); }); 

So, we import express and add an instance of express which conventionally we name app

var app = express(); 

In express everything works through app.

In our code when a server receives a get request on / and runs a function

app.get('/', function (req, res) {
    res.send('Hi!')
})

And that’s exactly how express works

A series of when receive a request with this method on this route run this/these function(s)

The last step is to make our server listen to a specific port

I select default port for http protocol 80

app.listen(port, function () {
    console.log('Server listening on ' + port);
}); 

So, let’s run our script with

root@e47199b3c130:/hello_nodejs# node index.js
(node:269) ExperimentalWarning: The ESM module loader is experimental.
Server listening on 80

and since 80 is the default http port go to http://localhost/

Browse to localhost

Although we are using the latest ECMAScript Modules the rest JavaScript code is still in ES5 way

Let’s make it cleaner and better with ES6+ style

We are going to use the block scope const instead of var

const app = express(); 
const port = 80; 

make our anonymous functions cleaner by using arrow functions

app.get('/', (req, res) => { res.send('Hi!') }); 

and use template literals to embed the port variable inside our string

app.listen(port, () => console.log(`Server listening on ${port}`)); 

Our code now looks like this

import express from 'express' 
 
const app = express(); 
const port = 80; 
 
app.get('/', (req, res) => { res.send('Hi!') }); 
 
app.listen(port, () => console.log(`Server listening on ${port}`)); 

Personal blog by Alex Kantas