How to setup Node/Express development environment

In the tutorial, we will show you how to setup Node/Express development environment that includes installation of Nodejs, NPM package, and ‘Express Application Generator’ optionally.

Installing Node

– Go to: https://nodejs.org/en/
– Download the LTS build that is “Recommended for most users”

download nodejs - LTS version

Double-clicking on the downloaded file and following the installation prompts:

install nodejs

Testing your Nodejs and NPM installation:

>node -v
v8.11.1

>npm -v
5.6.0

Create a ‘helloworld.js’, use ‘http’ module to create a Nodejs server createServer().

//Load HTTP module
var http = require("http");

//Create HTTP server and listen on port 8000 for requests
http.createServer(function (request, response) {

   // Set the response HTTP header with HTTP status and Content type
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body "Hello World"
   response.end('Hello World\n');
}).listen(8000);

// Print URL for accessing server
console.log('Server running at http://127.0.0.1:8000/')

Start the server:

>node helloworld.js
Server running at http://127.0.0.1:8000/

start nodejs express - print helloworld message

Using NPM

NPM is the most important tool for working with Node applications to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production.

>>> Step to do:

Create application directory

mkdir hellonodejs
cd hellonodejs

Create package.json file

With NodeJs application, ‘package.json’ file contains all the JavaScript “package” dependencies, including the package’s name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc.

Use the npm init to create ‘package.json’ file:

>npm init
...

Press ^C at any time to quit.
package name: (hellonodejs)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords: HelloNodeJs
author: JSA
license: (ISC)
About to write to C:\Users\pc\Desktop\nodejs\hellonodejs\package.json:

{
  "name": "hellonodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "HelloNodeJs"
  ],
  "author": "JSA",
  "license": "ISC"
}


Is this ok? (yes) yes

-> Check content of ‘package.json’ file:

{
  "name": "hellonodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "HelloNodeJs"
  ],
  "author": "JSA",
  "license": "ISC"
}

Install Express by NPM

Use command npm install express

>npm install express
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN hellonodejs@1.0.0 No description
npm WARN hellonodejs@1.0.0 No repository field.

+ express@4.16.3
added 50 packages in 8.935s

The dependencies of ‘package.json’ will now appear at the end of the ‘package.json’ file with ‘Express’.

{
  "name": "hellonodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "HelloNodeJs"
  ],
  "author": "JSA",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3"
  }
}

Use Express to create NodeJs server

Create an ‘index.js’ file in the root of the ‘hellonodejs’ application directory with content below:

var express = require('express')
var app = express()

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

app.listen(8000, function () {
  console.log('Example app listening on port 8000!')
})

app.get() function only responds to HTTP GET requests with the specified URL path (‘/’).

npm express project structure

Start the server

>node index.js
Example app listening on port 8000!

Go to http://127.0.0.1:8000, browser will display ‘Hello World!’.

start nodejs express - print helloworld message

Express Application Generator

We use the ‘Express Application Generator’ tool to generate an Express application skeleton.

>npm install express-generator -g
C:\Users\pc\AppData\Roaming\npm\express -> C:\Users\pc\AppData\Roaming\npm\node_modules\express-generator\bin\express-cli.js
+ express-generator@4.16.0
added 10 packages in 2.395s

Create an Express app named ‘hellonodejs’ with the default settings:

>express hellonodejs

  warning: the default view engine will not be jade in future releases
  warning: use `--view=jade' or `--help' for additional options


   create : hellonodejs\
   create : hellonodejs\public\
   create : hellonodejs\public\javascripts\
   create : hellonodejs\public\images\
   create : hellonodejs\public\stylesheets\
   create : hellonodejs\public\stylesheets\style.css
   create : hellonodejs\routes\
   create : hellonodejs\routes\index.js
   create : hellonodejs\routes\users.js
   create : hellonodejs\views\
   create : hellonodejs\views\error.jade
   create : hellonodejs\views\index.jade
   create : hellonodejs\views\layout.jade
   create : hellonodejs\app.js
   create : hellonodejs\package.json
   create : hellonodejs\bin\
   create : hellonodejs\bin\www

   change directory:
     > cd hellonodejs

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=hellonodejs:* & npm start

nodejs express project structure

Install all the dependencies for the ‘hellonodejs’ app by NPM:

cd hellonodejs
npm install

Run the app:

# Run on Windows
SET DEBUG=helloworld:* & npm start

# Run on Linux/macOS
DEBUG=helloworld:* npm start

express app running

See DEBUG command with logging:

hellonodejs>SET DEBUG=helloworld:* & npm start

> hellonodejs@0.0.0 start C:\Users\pc\Desktop\nodejs\hellonodejs\hellonodejs
> node ./bin/www

GET / 200 749.267 ms - 170
GET /stylesheets/style.css 200 8.511 ms - 111
GET /favicon.ico 404 24.351 ms - 1322

Project structure

/hellonodejs
    app.js
    /bin
        www
    package.json
    /node_modules
        [about 4,500 subdirectories and files]
    /public
        /images
        /javascripts
        /stylesheets
            style.css
    /routes
        index.js
        users.js
    /views
        error.jade
        index.jade
        layout.jade

package.json

{
  "name": "hellonodejs",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "http-errors": "~1.6.2",
    "jade": "~1.11.0",
    "morgan": "~1.9.0"
  }
}

– body-parser: parses/extract the body of an incoming HTTP request.
– morgan: An HTTP request logger middleware for node.
– cookie-parser: used to parse the cookie header and populate req.cookies

www file

/bin/www is the application entry point!

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');

/bin/www require() ‘app.js’ file.

app.js

The file creates an express application, sets up the application with various settings and middleware, and then exports the app from the module.

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

More details with ‘app.js’ file
– Import useful node libraries into the file using require():

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

require() modules from our routes directory:

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

– Set up the view (template) engine

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

– Add the middleware libraries into the request handling chain:

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

– Add route-handling to the request handling chain:

app.use('/', indexRouter);
app.use('/users', usersRouter);

– Add handler methods for errors and HTTP 404 responses:

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

– The last step is to add it to the module exports:

module.exports = app;

Routes

See ‘/routes/index.js’ file:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

It loads the express module, and uses it to get an ‘express.Router’ object.

Views

See ‘/views/index.jade’:

extends layout

block content
  h1= title
  p Welcome to #{title}

The above ‘/routes/index.js’ router will render template ‘/views/index.jade’.
-> Result:

express app running template

0 0 votes
Article Rating
Subscribe
Notify of
guest
723 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments