CodeNewbie Community 🌱

Shemona Singh
Shemona Singh

Posted on

Learning NodeJS Part 5: Setting up a Node (Express) Development Environment

In late fall of 2020, I went on a mission to better understand Node. I wanted to improve the way I use it, how I might be able to use more of its features, and moreover grow my front end knowledge to full stack. This series includes the notes I've compiled from my learnings over at The Odin Project. The lessons also include general web concepts necessary to better work with Node.


Now let's setup a basic Express app and breakdown some of its included files.

Express Application Generator

What is the Express Application Generator?

NPM can be used to globally install the Express Application Generator, a tool that creates skeleton Express web apps that follow MVC.

npm install express-generator -g

How do you create an Express app named "helloworld" with default settings

  1. Navigate to where you want to create it and run express helloworld
  2. It will generate a package.json file for you, with some dependencies. Install all dependencies via cd helloworld and npm install
  3. Run the app! DEBUG=helloworld:* npm start

Navigating Contents of a Node project

What version of Node/Express should you use?

Generally, you should use the most recent and long-term supported release of Node. Always use the latest version of Express.

What is the purpose of a package.json file?

You can manually use NPM to separately fetch each needed package. Typically dependencies are managed using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package".

It should contain everything NPM needs to fetch and run your application. If you were writing a reusable library you could use this definition to upload your package to the npm repository and make it available for other users!

What are development dependencies?

If a dependency is only used during development, you should instead save it as a "development dependency" so that your package users don't have to install it in production. For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

npm install eslint --save-dev

The following entry would then be added to your application's package.json:

"devDependencies": {
    "eslint": "^7.10.0"
  }
Enter fullscreen mode Exit fullscreen mode

What do named scripts allow us to do?

Named scripts are defined in the package.json and call NPM to execute run-script on whatever it is you've set it to. For example:

"scripts": {
  "lint": "eslint src/js"
}
Enter fullscreen mode Exit fullscreen mode

By adding this, we can now run npm run lint and it would run npm run-script eslint src/js for us.

Middleware

What is the role of middleware?

A middleware is just a plain JavaScript function that Express will call for you between the time it receives a network request and the time it fires off a response (i.e. it’s a function that sits in the middle). For example, you might have an authenticator that checks to see if the user is logged in, or otherwise has permission to access whatever they’re requesting.

Route functions end the HTTP request-response cycle by returning some response to the HTTP client whereas middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler.

Let's see what a typical middleware function looks like:

const myLogger = function(req, res, next) {
  console.log("Request IP: " + req.ip);
  console.log("Request Method: " + req.method);
  console.log("Request date: " + new Date());

  next(); // THIS IS IMPORTANT!
}

app.use(myLogger) 
Enter fullscreen mode Exit fullscreen mode
  • req - object with data about incoming request, ex. any parameters in the URL
  • res - object that represents the response that Express is going to send back to the user. You usually use the information in req to determine what you're going to do with res by calling res.send()
  • next - very important, tells express to move to the next middleware in the stack, but if you forget to call it then your app will pause and nothing will happen
  • app.use - is how you load your middleware function into Express so that it knows to use it. It will write these details to the console every time you get a network request

What is the only middleware function that is part of Express that allows us to serve files like images, CSS and JS?

express.static, or static().

How are errors handled?

By one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next).

Express comes with a built-in error handler, which takes care of any remaining errors that the app might encounter.

Routes, Views and Controllers

What are routes?

A route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), a URL path/pattern, and a function that is called to handle that pattern.

What are template or "view" engines?

Allow you to specify the structure you want the data to be outputted via a template. You can have placeholders for data that will be filled in when a page is generated.

Express supports many template engines.

How would one get started with using a template engine?

Start by installing the package containing your template library, then:

const express = require('express');
const path = require('path');
const app = express();

// 1 - Set directory to contain the templates ('views')
app.set('views', path.join(__dirname, 'views'));

// 2 - Set view engine to use, in this case 'some_template_engine_name'
app.set('view engine', 'some_template_engine_name');

// 3 - The appearance of the template will depend on what engine you use 
// Assuming that you have a template file named 
// "index.<template_extension>" that contains placeholders for data 
// variables named 'title' and "message", you would call 
// Response.render() in a route handler function to create and 
// send the HTML response:
app.get('/', function(req, res) {
  res.render('index', { title: "'About dogs', message: 'Dogs rock!' });"
});
Enter fullscreen mode Exit fullscreen mode

This brings us to the conclusion of foundations in Node and Express. To put all of your new knowledge to the test, I recommend following the Local Library tutorial over at MDN Web Docs. This project will use all the concepts I've mentioned in this 5-part series, and will truly help solidify a holistic view of Express.

Top comments (0)