Hello World Web App with Nodejs and Express

From Knowledge Center
Jump to: navigation, search

Install Nodejs:

$ apt update && apt install build-essential libssl-dev -y
$ curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh -o install_nvm.sh
$ bash install_nvm.sh
$ source ~/.profile
$ nvm install 8.9.4
$ nvm use 8.9.4
$ nvm alias default 8.9.4
$ nvm use default

Create the package.json for the dependencies:

We will also include unit testing:

{
  "name": "hello-world",
  "description": "hello world app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.12.0"
  },
  "devDependencies": {
    "mocha": "1.20.1",
    "supertest": "0.13.0"
  }
}

Our app.js

var express = require('express');
var app = express();
 
app.get('/', function (req, res) {
  res.send('Hello, World');
});
 
app.listen(process.env.PORT || 5000);
 
module.exports = app;

Run the App:

$ node app.js

Test it:

$ curl http://localhost:5000
Hello, World

Install the forever package to run the app as a daemon:

$ npm install -g forever
$ forever start app.js

Unit Testing:

test/test.js

var request = require('supertest');
var app = require('../app.js');
 
describe('GET /', function() {
  it('respond with hello world', function(done) {
    request(app).get('/').expect('Hello, World', done);
  });
});

script/test

#!/bin/sh
./node_modules/.bin/mocha ./test/test.js

Test it:

$ chmod +x script/test
$ ./script/test
  1 passing (81ms)

Source: - https://code.tutsplus.com/tutorials/setting-up-continuous-integration-continuous-deployment-with-jenkins--cms-21511