Getting Started With Node.js and Express
November 8, 2016
Node makes it extremely easy for developers to spin up a local server for web development. This tutorial uses the Express middleware framework to create a bare bone web app running on a local Node server
This tutorial assumes you are starting from scratch. It includes:
- 1. Installing Node.js
- 2. Creating a Node.js project
- 3. Adding the Express.js module
- 4. Launching the app
The first step will be installing the Node.js framework on your machine. Visit the official node.js and download the appropriate version for you.
Follow the installation wizard. Once complete, run the following:
If Node has been successfully installed, you should see something like:
Creating a Node.js project
Using the command line, navigate to your home directory and create a new folder called ‘myproject’:
mkdir myproject cd myproject
Now that you have an empty folder, you are ready to initialize a new node.js project. Every Node.js project requires a package.json file at it’s root. This file defines meta data related information (author, description) as well as dependencies for the project.
While you can simply create a package.json file yourself, node’s package manager (npm) makes this even easier. Simply run:
You will be prompted to enter information such as author, description for the project. Once complete, you will now see the generated package.json file in your project’s root directory.
Open your new package.json file and have a look. You will see a “main” attribute, which should point to an index.js file. This is the main script your server will run on initialization.
To create this main script file, run:
Adding the Express.js module
In order for the real web development to begin, you need to set up a web server for your project. While you could use node’s https module to build out basic routes, the Express framework makes running a web server even easier. Express is part of the popular MEAN stack, and allows for simplified routing. It’s easily configurable. Open your index.js file in your favorite text editor, and paste:
//Require Express module
var express = require('express');
//Define port for local web server
var port = 5000;
//Initialize your express app
var app = express();
//Create simple get route for the index of your app
//Listen on the defined port
console.log('Listening on port 5000')
This defines the initialization script for your Node.js app.
Launching the app
To launch the server, navigate to the root directory of your project and run:
If all goes according to plan, you should see something like:
Listening on port 5000
Finally, check your browser at localhost:5000 and you should see ‘Hello World!’
Congratulations! You are now up and running. In just a few short steps, you have a web server running on Node!