Skip to content

Instantly share code, notes, and snippets.

@itbakery
Last active February 11, 2018 16:34
Show Gist options
  • Save itbakery/f048daecd729ff7f4e8beb18192eb99e to your computer and use it in GitHub Desktop.
Save itbakery/f048daecd729ff7f4e8beb18192eb99e to your computer and use it in GitHub Desktop.
Javascript Front end develop

Use twitter bootstrap 4 with node

bootstrap 4 package

sudo npm install -g bootstrap
sudo npm install -g jquery
suod npm install -g nodemon
sudo yarn global add  bootstrap@4.0.0

create project

express project
cd project
npm install
npm install bootstrap 
npm install jquery 
npm install --save-dev nodemon

on the app.js

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

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www'));
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js'));
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); 
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); 

###then on template

<link href="/css/bootstrap.min.css" rel="stylesheet">
<script src="/js/jquery.js"></script>
<script src="/js/bootstrap.min.js"></script>

node web server

Due to the event-oriented nature of Node. Application is javascript app. nodejs will carry out to actions when the request from visitors arrive simultaneously. and come back toevent loop waiting to the event to happen again nodeserver

Install node

nodejs download

curl --silent --location https://rpm.nodesource.com/setup_9.x | sudo bash -
sudo dnf install gcc-c++ make
sudo dnf install nodejs
node -v

Install yarn

yarn download

sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo
sudo dnf install yarn
yarn --version

Install package

sudo npm install -g eslint
sudo npm install -g jshint
--or--
sudo yarn global install eslint
sudo yarn global install jshint

Test code

create folder demo1 copy text to file hellonode.js to editor

Recommend editor which support javascript code editor

//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/')

Code import "http" module and create a srever "createserver()" listen on port 8000 createserver() take function as an argument a callback function. Function will invoked when HTTP request is received

Open Terminal and run code

node hellonode.js
Server running at http://127.0.0.1:8000/

open browser to http://127.0.0.1:8000/

Return as html try code below and run node hellonode.js again

var http = require('http');


var server = http.createServer(function(req, res) {

res.writeHead(200, {"Content-Type": "text/html"});

res.write('<!DOCTYPE html>'+
'<html>'+
' <head>'+
' <meta charset="utf-8" />'+
' <title>My Node.js page!</title>'+
' </head>'+ 
' <body>'+
' <p>Here is a paragraph of <strong>HTML</strong>!</p>'+
' </body>'+
'</html>');
res.end();
});
server.listen(8080);

User npm

npm is tool to manage install node package (Javascript libraries)

Express is node package npm use plain-text definition file call package.json use npm init to create template package.json

mkdir myapp
cd myapp
npm init

# or 
npm init --yes
cat  package.json

Install Express library in myapp directory

npm install express
cat package.json

npm add dependencies section to package.json at the end of file npm create folder node_modules

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2"
  }
}

create index.js

use express library by import expresss module and create app with express() listen for HTTP request on port 8000. app.get() function only responds to HTTP Get request with specified URL path ('/') can calling function to return open editor can copy code 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!')
})

run in Terninal

node index.js
Example app listening on port 8000!

Open 127.0.0.1:8000

Development dependencies

if library dependency is used only development, you shold instaed save it as "development dependency" install Javascript Linting tool ESLint

npm install eslint --save-dev
cat package.json

option --save-dev npm add devDependencies section at end of file open editor add "lint": "eslint src/js" in scripts section

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint src/js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2"
  },
  "devDependencies": {
    "eslint": "^4.17.0"
  }
}

Run script

npm run-script lint
npm run lint
# or
yarn run lint

Install Express Application Generator

Express application generator use tool express-generator to quickly create application skeleton

sudo npm install express-generator -g
# or
sudo yarn global add express-generator

express -h

to create express app nameed "helloworld"

express helloworld

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


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

   install dependencies:
     $ cd helloworld && npm install

   run the app:
     $ DEBUG=helloworld:* npm start

follow instruction

cd helloworld && npm install
DEBUG=helloworld:* npm start

> helloworld@0.0.0 start /home/mee/reactApp/helloworld
> node ./bin/www

  helloworld:server Listening on port 3000 +0ms

Open browser 127.0.0.1:3000

Routeing

Express support routing to application endpoints respond to client request. supprt all HTTP method Basic route can use (app.METHOD) app.get() will handle get request and app.post() handle post request app.all() will handle all request that response will handle from callback function

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

// 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')
})

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})

Route paths

Route path , in combination with request will define the endpoint on request. Route path can be

  • String
  • string patterns or reqular expressions
  • combination ?, +, *, and ()

Example

app.get('/', function (req, res) {
  res.send('root')
})

app.get('/about', function (req, res) {
  res.send('about')
})

app.get('/random.text', function (req, res) {
  res.send('random.text')
})

create path match acd or abcd

app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

match abcd, abbcd, abbbcd, and so on.

app.get('/ab+cd', function (req, res) {
  res.send('ab+cd')
})

match abcd, abxcd, abRANDOMcd, ab123cd,

app.get('/ab*cd', function (req, res) {
  res.send('ab*cd')
})

match /abe and /abcde

app.get('/ab(cd)?e', function (req, res) {
  res.send('ab(cd)?e')
})

match anything with an “a” in the route name.

app.get(/a/, function (req, res) {
  res.send('/a/')
})

match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.

app.get(/.*fly$/, function (req, res) {
  res.send('/.*fly$/')
})

Route parameter

pass parameter in URL segments. Route capture the values by their position in url. and populated in req.params with name of the route parameter and value

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }

test

app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})

use hyphen (-) and dot(.) to url parameter more meaning

Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }

or

Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }

control type of value by use ()

Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

can provide multiple call back function

Route act as middle ware pass handle request to next function. single call back function

app.get('/example/a', function (req, res) {
  res.send('Hello from A!')
})

more than one call back

app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})

And array of callback functions

var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

var cb2 = function (req, res) {
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])

compination of independent fucntions and arrays of the function

var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from D!')
})

Response methods

methos on response object (res)

Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

app.route()

you can create chainable route handle same path but different http method

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })

express.Router()

use Router class to create modular, mountable route handlers. Router instance is middleware of routing system. create modular by create router file name birds.js

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

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router

Load to app

var birds = require('./birds')

// ...

app.use('/birds', birds)

The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

Summary

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

architect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment