Development

Local Development with Node and Express

Create your Server

If you are working with React and webpack, you probably or mostly never have to create your own local server. If you ever wonder how it works under the hood, here is a simple way to get a local server up and running in no time.

Install Node

First we need Node. You probably have node installed. If not, and you’re on a Mac use Homebrew:

# Install node with Brew:
brew install node
node -v

Your First Server

Create a index.js file:

mkdir my-cool-app && cd my-cool-app && touch index.js

Then on our index.js :

const http = require( 'http' )
// Create and start a server with the
// createServer method from http package
const server = http.createServer( ( req, res ) => {
console.log(req.url)
res.end( 'Hello node.js' )
} )
// start our server to start taking request
server.listen(3000)

To learn more about the Node http package, use the following link to learn all about http.

Finally, run index.js with:

node index.js
view raw .run-node hosted with ❤ by GitHub

Go to your browser and enter http://localhost:3000/ in your browser. You should see the text, ‘Hello Node.js.’

Request and Response

To have different responses based on different URLs, we now change our respond:

const http = require( 'http' )
const server = http.createServer( ( req, res ) => {
console.log( req.url )
switch( req.url ) {
case '/':
res.end( 'The Homepage' )
break;
case '/about':
res.end( 'The About Page' )
break;
case '/contact':
res.end( 'The Contact Page' )
break;
default:
res.writeHead( 404 )
res.end()
}
} )
server.listen(3000)

Let’s restart Node: CTRL + C. Run  node index.js. Go to localhost:3000 and navigate the routes:

To see your request information, open developer tools/network/status. It will show the status code from the request.

What about adding HTML Files to our routes? In the same directory of index.js, create:

touch index.html about.html contact.html 404.html
view raw .bash hosted with ❤ by GitHub

With Emmet, it is as easy as typing ! or doc and hit the ENTER KEY. Your file will have the HTML code necessary to run. If you use Visual Code like me, support for Emmet snippets and expansion is built right into Visual Studio Code; no extension required.

Emmet takes the snippets idea to a whole new level. You can type CSS-like expressions that can be dynamically parsed, and produce output depending on what you type in the abbreviation. Emmet is developed and optimized for web developers whose workflow depends on HTML/XML and CSS but can be used with programming languages too. Bookmark this: Emmet Cheat Sheet.

Now, add a navigation. Let’s use Emmet one more time.

Between the body tags, go ahead and type ul>li*3>a and hit enter. This will create an unordered list with three items and a tags. Add your links, as seen in this screenshot, and then add a h1 tag on each of the pages named Homepage, About, Contact, and Page Not Found. Your files should look like this:

Let’s update index.js.

const http = require( 'http' )
// import 'fs' a file system module which
// helps interact with files on our server
const fs = require('fs')
// The 'readFileSync' method from 'fs'
// reads the content of each file and returns it.
const homePage = fs.readFileSync('index.html')
const aboutPage = fs.readFileSync('about.html')
const contactPage = fs.readFileSync('contact.html')
const notFoundPage = fs.readFileSync('404.html')
const server = http.createServer( ( req, res ) => {
console.log( req.url )
switch ( req.url ) {
case '/about':
res.end(aboutPage)
break;
case '/contact':
res.end(contactPage)
break;
case '/':
res.end(homePage)
break;
default:
res.writeHead(404)
res.end(notFoundPage)
}
} )
server.listen(3000)
view raw index.js hosted with ❤ by GitHub

Restart the server with CTRL + C and run  node index.js . Go to: http://localhost:3000; you’re now navigating your HTML files.

 

Express

Express is a minimal and flexible NodeJS web application framework that provides a robust set of features for web and mobile applications. Express provides a layer of abstraction to make handling web traffic and APIs easier. In short, Express did for NodeJS what Bootstrap did for HTML/CSS and responsive web design.

Some of the advantages of using Express are:

  • Almost the standard for Node.js web middleware
  • Simple, minimalistic, flexible, and scalable
  • Fast app development
  • Fully customizable
  • Low learning curve
  • Majorly focused on browsers, making templating and rendering an almost out-of-the-box feature

Before we install Express, we need to create a package.json file. On your root directory, run:

# It will ask you a bunch of questions, and then write a package.json for you.
npm init
# or generate an empty npm project without going through an interactive process.
npm init -y
view raw .bash hosted with ❤ by GitHub

If you’re not familiar with npm init and its flags, I recommend running npm help init for definitive documentation on these fields and exactly what they do.

Now that we have our package.json in our project. Let’s go ahead and install Express:

npm install express
view raw .bash hosted with ❤ by GitHub

Let’s refactor our index.js to work with Express:

// Require Express Module
const express = require('express')
// Calls express function to start new Express app.
const app = express()
app.listen( 3000, () => {
console.log( 'App listening on port 3000' )
})
view raw index.js hosted with ❤ by GitHub

Previously we create a server and started with:

const server = http.createServer( (req, res) => {
...
} )
server.listen(3000)
view raw index.js hosted with ❤ by GitHub

We have to take care of importing http, fs , other packages, and also the request and response object; but with Express, we achieve the same thing.

Run CTRL + C and  node index.js . Check your terminal. It should now log from Express, your routes are probably broken.  We’ll take care of that next.

node index.js
# This gets log to the terminal
App listening on port 3000
view raw .bash hosted with ❤ by GitHub

Routing with Express

You define routing using methods of the Express app object that correspond to HTTP methods—for example, app.get() to handle GET requests and app.post() to handle POST requests.

The following code is an example of a very basic route.

// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage')
})
view raw method.js hosted with ❤ by GitHub

To learn more about Express routing click here. For now, let’s add routing to our app go to index.js.

const express = require('express')
const app = express()
// path is a built in module in Node
// It Helps get the specific path to the files
const path = require('path')
app.listen( 3000, () => {
console.log('App listening on port 3000')
})
app.get('/', ( req, res ) => {
res.sendFile( path.resolve( __dirname, 'index.html') )
})
app.get('/about', ( req, res ) => {
res.sendFile( path.resolve( __dirname, 'about.html') )
})
app.get('/contact', ( req, res ) => {
res.sendFile( path.resolve( __dirname, 'contact.html') )
})
app.get('*', (req, res) => {
res.sendFile( path.resolve(__dirname, '404.html'))
})
view raw index.js hosted with ❤ by GitHub

Express adds things like the sendFile method which makes it easier to write request handler functions.

That’s it! Run CTRL + C and node index.js and navigate within your app.

 

Serving Static Files

Express has this special function, app.use(), which mounts the specified middleware function or functions at the specified path. The middleware function is executed when the base of the requested path matches path. This special function, express.static(), is a built-in middleware function in Express. It serves static files and is based on serve-static.

What is middleware? Middleware is a software that bridges gaps between other applications, tools, and databases in order to provide unified services to users. It is commonly characterized as the glue that connects different software platforms and devices together.

app.use("/", (req, res, next) => {
console.log("I am a middleaware")
next()
})

Create a directory:

mkdir public && cd public
# Create the sub folders
mkdir css js
# Create the style file
cd css && touch styles.css
# Create the script file
cd ../js && touch index.js
view raw .bash hosted with ❤ by GitHub

Add this code on your index.js file in the root of your app:

const express = require('express')
const app = express()
// path is a built in module in Node
// It Helps get the specific path to the files
const path = require('path')
// Add the Public Folder for Assets
app.use(express.static('public'))
app.listen( 3000, () => {
console.log('App listening on port 3000')
})
// App Routes
app.get('/', ( req, res ) => {
res.sendFile( path.resolve( __dirname, 'index.html') )
})
app.get('/about', ( req, res ) => {
res.sendFile( path.resolve( __dirname, 'about.html') )
})
app.get('/contact', ( req, res ) => {
res.sendFile( path.resolve( __dirname, 'contact.html') )
})
app.get('*', (req, res) => {
res.sendFile( path.resolve(__dirname, '404.html'))
})
view raw index.js hosted with ❤ by GitHub

To reference styles.css in index.html, add in index.html and on all your HTML files between the <head> in the following lines:

<link rel="stylesheet" href="css/styles.css">
<script src="js/index.js"></script>

Let’s make sure we are reading the styles and script; on your style.css add:

body {
background-color: beige
}

In your index.js, be sure that this is the new index.js the one on our public folder on the js directory, and is not our root index.js.

document.addEventListener("DOMContentLoaded", function(event) {
console.log( 'Hello From Public' );
});
view raw index.js hosted with ❤ by GitHub

That’s it! You have an app running locally with Node and Express.

We learned how to install and run a Node application locally and leverage it with Express. We also learned how to serve static files with express.static().

Automatic Server Restart with Nodemon

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server, making it perfect for development. We have been starting and stopping our server each time we make a change on index.js, but with Nodemon, we don’t have to that anymore.

Let’s install Nodemon: npm i nodemon --save-dev. Now update your package.json.

...
"scripts": {
"start": "nodemon index.js"
}

So instead of node index.js, we now run our app with npm start.

I hope this article helps you understand what happens under the hood on some of the most popular JavaScript bundlers.

Comments

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress