Introduction
Node.js, a javascript runtime based on Chrome’s V8 JavaScript engine, is revolutionary in its own right. Node.js enables developers to use Javascript, which typically runs on a browser, to write server-side code. For Javascript developers, in particular, this is heaven-sent as they can now work on the backend without learning a new programming language.
However, working with Node.js itself can be a bit of a hard nut to crack, particularly for new developers. Tasks like creating servers, listening for requests, parsing request bodies and sending back a response require writing complex server-side logic. This can get overwhelming, particularly for beginners. This is where Express comes in to save the day.
This article is the first part of a series of articles providing a detailed comprehensive introduction to using Express. This article covers how to set up your Express project and its package.json
file. Additionally, it covers npm scripts and how to install and use Nodemon and Express. Finally, the article covers how to use Express to create a node server that listens for requests and sends back a response.
Prerequisites
- Fundamental knowledge of HTML, CSS and JavaScript
- Fundamental knowledge in Node.js is desirable but not a must-have
- A code editor and a browser. This article will use VS Code and Chrome respectively.
- Node.js and Node Package Manager(NPM) Installed on your machine
- An internet connection
What is Express?
From its official documentation, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Additionally, its HTTP utility methods and middleware can be used in creating robust Application Programming Interfaces (API) quickly and easily.
A framework is reusable code written by other people that you use to structure your programs. A framework provides ready-made components or solutions we can use to speed up development
An API is a software intermediary that allows programs to communicate with each other without user intervention
As a framework, Express provides you with tools you can use to perform the following tasks:
- Create servers and listen for requests
- Parse incoming requests
- Match incoming requests with appropriate routes
- Send back a response
Why use Express?
The following are some of the reasons to use Express:
- It provides reusable built-in components which allow you to build a node application faster
- It allows you to focus on the unique business logic of your application instead of complex server-side logic
- It is flexible and pluggable allowing you to add other modules to help in your development
Getting started
A general rule while building Node.js applications is to have a package.json
file which is stored in the root directory of a project.
The package.json
file will store metadata such as the name of the project, its description and its author. Importantly though, it will store metadata on the packages and dependencies needed to run the project. NPM uses the package.json file to start your project, run scripts, install dependencies and publish a project on npm’s registry.
dependencies are the external code or packages that a project requires for it to run. There are two types of dependencies in a package.json:
- dependencies: packages required by a project in production
- devDependencies: Packages that are only needed for local development and testing
Additionally, for you to install any packages in your project, such as Express in this case, or to make your project publicly available, you need a package.json
file.
Therefore the first step in creating an express project will be creating a package.json
file for the project.
To create a package.json file for the project:
- Open a terminal window and create a folder called ExpressProject by typing
mkdir ExpressProject
. You can, however, give the folder any name you like. - Navigate into the folder by typing
cd ExpressProject
- Create a package.json file by typing
npm init
. This opens a utility that walks you through creating a package.json file.
This utility will provide a guide to creating a package.json
file. The utility will show prompts where you can type in the information to be stored in the package.json
file. You can also press enter
without typing any value for a given field to use the suggested value, provided in parentheses, or leave it blank.
The package.json
file can be edited later in the code editor. Do not panic if you make typing errors
The following are prompts that will show up and what to do once they show up:
package name: (expressproject)
- pressenter
the package name depends on the name you gave your folder
version: (1.0.0)
- pressenter
description
- Type a short description of what your project does and pressenter
once donedescription: A Node.js application using Express
test command:
pressenter
git repository:
pressenter
If you have a git repository, paste a link to the repository. However, to keep this tutorial beginner friendly, no git repository is required
keywords:
pressenter
author:
provide the name of the author of the project and pressenter
.license: (ISC)
pressenter
Is this OK? (yes)
This is accompanied with a preview of thepackage.json
file that is going to be created is provided. pressenter
If you notice an error in the package.json file, it is still okay to press
enter
as you can edit thepackage.json
file in the editor.- Type
code .
to open the folder in Vs Code
Once done you should have such a package.json
file created in your project folder.
Installing packages needed for the project
This project will require installing two packages namely Nodemon and Express. The packages installed will be saved in a folder called node_modules
which will be created automatically once a package is installed.
Installing Nodemon
Nodemon is a tool that automatically restarts a node application when file changes are detected in the application's directory. This is handy as you won't need to manually restart a Node Server every time you make changes to a file.
You can skip this step if you already have Nodemon installed.
To install nodemon
- Enter
npm install -g nodemon
in the terminalthe -g flag is used to install Nodemon globally in your system. This way, you can use Nodemon anywhere on your computer and not just in your current project directory.
In case of permission errors if you're using a linux sytem, use sudo npm install -g nodemon
and press enter
Installing Express
To install express:
- Enter
npm install express
in the terminal
After installing Nodemon and Express in your project, open your package.json
file.
{
"name": "expressproject",
"version": "1.0.0",
"description": "A Node.js application using Express",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Collins Kariuki",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"nodemon": "^2.0.20"
}
}
Notice a new field called dependencies
has been added to the package.json
file. This field has values showing the dependencies needed for our project, in this case, Express and Nodemon together with the versions used in the project.
When you receive a Node project with a
package.json
file, runningnpm install
in the project directory will install all the needed dependencies for the project.
Another section of interest in the package.json
file is "main": "index.js"
. This shows the entry point to your application. When you run your node application, Node will use the indicated main file, in this case, index.js
to start your application.
Therefore when creating your application, you need to create a file called index.js
which will act as the entry point to your application. However, you can give the file a different name. When you do this, make sure to make the change in the package.json
file to reflect the change in the main file.
Edit "main": "index.js"to
"main": "app.js". You can give your main file any name you like. This article will use
app.js` as the main entry point to the application.
In the package.json
file script is another important section. Script allows you to write your own npm scripts with you can run using npm run <script-name>
npm scripts are common shell commands stored in the script section of a
package.json
file to automate repetitive tasks such as running your node application
Typically, you run node applications using by entering Node <name of application file>
in the terminal. For instance, if your node application is stored in a file called app.js
, you run the application by entering node app.js
in the terminal opened at the folder containing the app.js
file.
However, since you installed Nodemon to restart your server anytime changes are made in the file, use Nodemon to run your node application.
To run a node application using Nodemon enter nodemon <name of application>
in the terminal.
For instance, to run a node application in a file called app.js
use nodemon app.js
To make running your app even easier, use npm scripts.
In your package.json file, edit the script section by adding the line "start": "nodemon app.js"
. The script section of your package.json
file should now look like this:
{
"name": "expressproject",
"version": "1.0.0",
"description": "A Node.js application using Express",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js"
},
"author": "Collins Kariuki",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"nodemon": "^2.0.20"
}
}
The script we have added is called start, therefore, to run it, typically you'd run npm run start
in the terminal. This will start your node application once you add server-side logic to it.
However, with npm, there are special script names associated with common tasks when creating a node application. These scripts have aliases, such that you don't need to write the command run to execute them in a terminal. You can simply run their alias. These script aliases are:
npm start
alias fornpm run start
npm stop
alias fornpm run stop
npm test
alias fornpm run test
npm restart
alias fornpm run restart
Therefore, to start a node application, you can simply execute npm start
instead of npm run start
. However, both commands work but the former saves you a few characters. Likewise, to restart a node application, you can simply execute npm restart
instead of npm run restart
. However, for other scripts without aliases, you need to execute npm run <script name>
To start node applications, this article will use npm start
. Once you run this command, Node.js will look in your package.json
file and execute the command associated with the script. In this case, Node.js will execute nodemon app.js
Creating a server using Express
To create a server using Express, follow the following steps:
- Create a new file in the project folder and name it
app.js
. Open it in the code editorthe file is named
app.js
because, in thepackage.json
file, the entry point of the Node application was set to "main": "app.js". If your main section in thepackage.json
is set to a different javascript file name such asindex.js
name your fileindex.js
- Import Express into your
app.js
file and save it to a constant. To use Express in your file you first need to import it into your file usingrequire()
and save it to a constant. Enter the following line to import Expressconst express = require('express');
You can give your constant any name you like, but it is good practice to give the constant the name of the package you are importing, in this case, express. You can also use a variable instead of a constant, but constants are generally preferred because you don't want any changes made to them.
- Create an express application and store it in a constant by running express as a function
const app = express();
The line above initialises an Express object which will store Express methods in the constant named
app
. This constant will be used to access Express methods and functionality. Create a middleware that will be executed for every incoming request and sends back a response
app.use((req,res,next) => { res.send('<h1>Hello from an Express server</h1>') })
In the code above, the function
use()
allows you to add express middleware functions. A middleware function is a function that has access to the request object(req), the response object(res) and the next function in the application request-response cycle. The code above has one middleware function to handle requests and responses, the middleware function is(req,res,next) => { res.send('<h1>Hello from an Express server</h1>')
The argument req represents the request object, res is the response object and next is a function that if called, executes the next middleware in line. Whereas you can give these arguments any name you like, their order matters. The first argument will always be the request object, the second the response object and next the final argument. This middleware function will be executed every time a request is made. In the middleware function the line
res.send('<h1>Hello from an Express server</h1>')
is used to send back a response once a request is made. To send a response, you use the res object which is an argument in the middleware function. The response object, res has a function called send() that is invoked to send the actual response which in this case is a simple
h1
element wrapped in quotes.Set the server to listen for requests at port 3000
app.listen(3000);
- Start your node application by executing the following command in the terminal
If successful your code editor should display something similar to this:npm start
- Go to your browser and enter
http://localhost:3000
Entering the localhost:3000 sends a request to your running node server, listening for requests at port 3000. Your running server in turn sends a response and you should see such a screen showing the response sent from your node server
Next Steps
After successfully setting up a node server using Express, the next step is to dive into express middleware which is discussed in the next article which is a follow to this article.