Node.js and Express: A Lightweight Minimalist Framework

Kristin Ponsonby
4 min readJan 29, 2022

--

Since graduating from bootcamp, I’ve been learning a few different new technologies and frameworks to keep my skills sharp and stay on top of my game. One I kept running across was Node.js. Unlike JavaScript or Ruby, Node.js is not in fact a framework or language. It is actually a runtime environment. In simple terms, Node.js is just a way to run JavaScript outside the browser. JavaScript is traditionally a client side language. What Node enables you to do is run Javascript server side. The most common use case for Node.js is to create a simple web server for a JS application. In this article we will take a closer look at some of the basic features of Node.js and a framework called Express.

Getting Started

Getting a Node.js server up and running is actually quite simple. In this example we are going to use Express as our skeleton. From inside your JavaScript project folder, create a file. Let’s call it, app.js. You are going to use the require keyword to enable the request library. Then you will create a port variable that tells your server what port to listen to. Lastly create your app variable to run express. In this example, I made a simple fetch request to the Fruityvice public API.

const express = require(“express”);
var request = require(“request”);
const app = express();
const port = 3001
app.get("/fruits", (req, res) => {
request("https://fruityvice.com/api/fruit/all",
function(error, response, body) {
if (!error && response.statusCode == 200) {
var parsedBody = JSON.parse(body);
res.send(parsedBody);
}
})
});
app.listen(port, () => {
console.log(`starting on ${port}`);
});

To boot up your shiny new server simply run:

$node app.js

The Global Object

So you’re probably familiar with the term global scope. In Node, variables and functions are not automatically added to the global object. They are only available in the local file they are defined in. We want to avoid defining variables and functions in the global scope so we implement something called modules. This way, two functions or variables in different files with the same name don’t overwrite each other. Those variables and functions are private to that file, in object-oriented programming terms.

Modules

In Node, every file is a module. The variables and functions inside that file are scoped to that module, they are not available outside of that module. For example, App.js may be your ‘main module’. You would have to add module.export.(function) or (variable) to make those variables or functions available outside of the App.js module.

Implementation

To load a module we use the ‘require’ function. One important thing to note is that we don’t have this function in browsers.


require(‘path-of-file’)

When loading a module, it is considered best practice to store the results in ‘const’. Because again, we don’t want to accidentally overwrite the value of our module.

The Events Module

One of the core concepts in Node.js is the events module. Events are basically a signal that something has happened in our application.


const EventEmitter = require(‘events’) // a class
const emitter = new EventEmitter(); //an actual object, or an instant of the class EventEmitter
//Register a listener
emitter.on(‘messageLogged’, function(arg){. // or e
console.log(‘Listener called’);
});
//or ECMA6 syntax with arrow function:
emitter.on(‘messageLogged’, (arg) => {
console.log(‘Listener called’);
});
//Raise an event
emitter.emit(‘messageLogged, {id: 1, url: ‘http://..’});
//emit means producing a noise, signaling.
//Order matters. the listener must be defined before raising the event.//Raise: logging (data: message)

Working with Express: A Lightweight Minimalist Framework

Express is a web application framework for Node that gives our app a skeleton-a structure. It is useful for working with API’s and building single-page or multi-page applications. Express makes it super quick and easy to get a backend server up and running.

Once you’ve got the code above in your app.js file, there’s a few different things you could do next. The first thing you’ll want to do is install a dependency called Nodemon by running:

$node i -D nodemon

If you’ve played around with your server a bit you probably noticed you have to restart your sever every time you make changes to your files. This makes for super tedious development. Nodemon automatically monitors your source code and restarts your server when you make changes. Neat!

Basic Routing

According to the Express documentation, “Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).” So if you’ve worked with Ruby on Rails for example, this should be a pretty familiar concept. Defining a route in Express is simple:

app.METHOD(PATH, HANDLER)

app is just your instance of express, method refers to the type of HTTP request you want to make, path is your path on the server, and lastly handler is the function you want to run when the route is matched. Here is a simple example of a route in an Express application:

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

This code will respond with ‘Hello World’ in your browser.

Template Engines

View engines, or template engines, are very useful in Express applications for for rendering HTML web pages. There are many template engines out there you could use for your application. Pug, EJS, Mustache, to name a few. The most commonly used is probably EJS, which stands for embedded JavaScript. With this engine, you can generate HTML with vanilla JavaScript. The first thing you will do is create a ‘Views’ folder inside your applications directory. Then create a file called index.ejs. Populate your file with some boilerplate to test it out. Before this will work, you will need to set up your view engine. For this example we’ll use EJS.

In your app.js file we created earlier, write the following code:

app.set('view engine', ejs)

Save your file and restart your server. You should see in your browser the HTML you wrote in index.js. Cool!

--

--

Kristin Ponsonby
Kristin Ponsonby

Written by Kristin Ponsonby

Software engineer and advocate for women in STEM.

Responses (1)