Sunday, February 12, 2017

Expressjs with Compound

First steps: install compound and generate app

  1. if not already installed, install nodejs (v 0.8.0+) - http://nodejs.org/download/. If you have node installed you can test your version with: node --version
  2. install compound using npm. Doing this globally enables the compound command line tool. You might need to sudo.
    npm install compound -g or sudo npm install compound -g
  3. generate the todo-list app using the compound command line. This creates an application with the default compoundjs structure.
    compound init todo-list-app
  4. install the dependencies (see package.json for default dependencies. They will be downloaded to the node_modules dir)
    cd todo-list-app && npm install
Now that we have the initial compound app structure, we can run your new compoundjs application.
Let's run the command node . and then open http://localhost:3000/ in a browser.
NOTE the node . command is simple way to run the application in the current directory. You also can run node server.js or coffee server.coffee or even compound server. the result will be the same, we will learn the differences later.
After opening localhost:3000 in a browser we will see a welcome page with some links and debug info (this appears after you click on the corresponding link). This is a static file located ./public/index.html. Everything in the ./public dir will be available to your app as static content so client-side javascripts and stylesheets should be saved here.
NOTE some javascript files and stylesheets may be generated from coffee or sass / less / stylus. Sources for these files are located at ./app/assets and compiled automatically using co-assets-compiler extension module.
https://github.com/compoundjs/guides/blob/master/basics/crash-course.md

1. C:\Node4Express>npm install compound -g
npm WARN deprecated jade@0.26.3: Jade has been renamed to pug, please install th
e latest version of pug instead of jade
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher
 to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@2.0.3: graceful-fs v3.0.0 and before will fail o
n node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible
. Use 'npm ls graceful-fs' to find it in the tree.
C:\Users\User\AppData\Roaming\npm\compound -> C:\Users\User\AppData\Roaming\npm\
node_modules\compound\bin\compound.js
C:\Users\User\AppData\Roaming\npm\rw -> C:\Users\User\AppData\Roaming\npm\node_m
odules\compound\bin\compound.js
C:\Users\User\AppData\Roaming\npm
`-- compound@1.2.4
  +-- coffee-script@1.7.1
  | `-- mkdirp@0.3.5
  +-- ejs-ext@0.1.4-5
  +-- inflection@1.2.7
  +-- jade-ext@0.0.7
  +-- kontroller@0.0.15
  | `-- mocha@1.17.1
  |   +-- commander@2.0.0
  |   +-- debug@2.6.1
  |   | `-- ms@0.7.2
  |   +-- diff@1.0.7
  |   +-- glob@3.2.3
  |   | +-- graceful-fs@2.0.3
  |   | +-- inherits@2.0.3
  |   | `-- minimatch@0.2.14
  |   |   +-- lru-cache@2.7.3
  |   |   `-- sigmund@1.0.1
  |   +-- growl@1.7.0
  |   `-- jade@0.26.3
  |     +-- commander@0.6.1
  |     `-- mkdirp@0.3.0
  +-- railway-routes@0.0.12
  `-- yaml-js@0.1.4

C:\Node4Express>node --version
v6.9.5

2. C:\Node4Express>compound init todo-list -app
create  todo-list
create  todo-list\app\
create  todo-list\app\assets\
create  todo-list\app\assets\coffeescripts\
create  todo-list\app\assets\stylesheets\
create  todo-list\app\models\
create  todo-list\app\controllers\
create  todo-list\app\helpers\
create  todo-list\app\tools\
create  todo-list\app\views\
create  todo-list\app\views\layouts\
create  todo-list\db\
create  todo-list\db\seeds\
create  todo-list\db\seeds\development\
create  todo-list\log\
create  todo-list\public\
create  todo-list\public\images
create  todo-list\public\stylesheets\
create  todo-list\public\javascripts\
create  todo-list\node_modules\
create  todo-list\config\
create  todo-list\config\locales\
create  todo-list\config\initializers\
create  todo-list\config\environments\
create  todo-list\app\assets\coffeescripts\application.coffee
create  todo-list\app\assets\stylesheets\application.styl
create  todo-list\app\tools\database.js
create  todo-list\config\environment.js
create  todo-list\config\environments\development.js
create  todo-list\config\environments\production.js
create  todo-list\config\environments\test.js
create  todo-list\config\routes.js
create  todo-list\config\autoload.js
create  todo-list\db\schema.js
create  todo-list\public\index.html
create  todo-list\public\stylesheets\bootstrap.css
create  todo-list\public\stylesheets\bootstrap-responsive.css
create  todo-list\public\images\glyphicons-halflings-white.png
create  todo-list\public\images\glyphicons-halflings.png
create  todo-list\public\images\compound.png
create  todo-list\public\javascripts\rails.js
create  todo-list\public\javascripts\bootstrap.js
create  todo-list\public\javascripts\application.js
create  todo-list\public\favicon.ico
create  todo-list\Procfile
create  todo-list\README.md
create  todo-list\package.json
create  todo-list\server.js
create  todo-list\.gitignore
create  todo-list\config\database.js
create  todo-list\app\views\layouts\application_layout.ejs
create  todo-list\app\controllers\application_controller.js

install the dependencies (see package.json for default dependencies. They will be downloaded to the node_modules dir)
cd todo-list-app && npm install
.. long long list of structures

Let's run the command node . and then open http://localhost:3000/ in a browser.
NOTE the node . command is simple way to run the application in the current directory. You also can run node server.js or coffee server.coffee or even compound server. the result will be the same, we will learn the differences later.
C:\Node4Express\todo-list>node .
express deprecated app.configure: Check app.get('env') in an if statement config
\environment.js:6:9
connect deprecated methodOverride: use method-override npm module instead config
\environment.js:16:25
express deprecated app.configure: Check app.get('env') in an if statement config
\environments\development.js:6:9
(node:8156) DeprecationWarning: sys is deprecated. Use util instead.
Compound server listening on 0.0.0.0:3000 within development environment

Integrating Express with MySQL

MySQL

Modulemysql Installation
$ npm install mysql
Example
var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'dbuser',
  password: 's3kreee7'
})

connection.connect()

connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
  if (err) throw err

  console.log('The solution is: ', rows[0].solution)
})

connection.end()

More at http://expressjs.com/en/guide/database-integration.html#mysql

C:\Node4Express\pms4express>npm install mysql
pms4express@0.0.0 C:\Node4Express\pms4express
`-- mysql@2.13.0
  +-- bignumber.js@3.1.2
  +-- readable-stream@1.1.14
  | +-- core-util-is@1.0.2
  | +-- isarray@0.0.1
  | `-- string_decoder@0.10.31
  `-- sqlstring@2.2.0

Frameworks built on Express

Frameworks built on Express

Several popular Node.js frameworks are built on Express:
  • Feathers: Build prototypes in minutes and production ready real-time apps in days.
  • ItemsAPI: Search backend for web and mobile applications built on Express and Elasticsearch.
  • KeystoneJS: Website and API Application Framework / CMS with an auto-generated React.js Admin UI.
  • Kraken: Secure and scalable layer that extends Express by providing structure and convention.
  • LEAN-STACK: The Pure JavaScript Stack.
  • LoopBack: Highly-extensible, open-source Node.js framework for quickly creating dynamic end-to-end REST APIs.
  • MEAN: Opinionated fullstack JavaScript framework that simplifies and accelerates web application development.
  • Sails: MVC framework for Node.js for building practical, production-ready apps.
  • Bottr: Framework that simplifies building chatbot applications.
  • Hydra-Express: Hydra-Express is a light-weight library which facilitates building Node.js Microservices using ExpressJS.
  • Blueprint: Highly-configurable MVC framework for composing production-ready services from reusable components

Expressjs : Static Files

Serving static files in Express

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files directly. For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
To use multiple static assets directories, call the express.static middleware function multiple times:
app.use(express.static('public'))
app.use(express.static('files'))
Express looks up the files in the order in which you set the static directories with the express.static middleware function.
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:
app.use('/static', express.static(path.join(__dirname, 'public')))
More at http://expressjs.com/en/starter/static-files.html

Expressjs Routing

Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one or more handler functions, which are executed when the route is matched.
Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
This tutorial assumes that an instance of express named app is created and the server is running. If you are not familiar with creating an app and starting it, see the Hello world example.
The following examples illustrate defining simple routes.
Respond with Hello World! on the homepage:
app.get('/', function (req, res) {
  res.send('Hello World!')
})
Respond to POST request on the root route (/), the application’s home page:
app.post('/', function (req, res) {
  res.send('Got a POST request')
})
Respond to a PUT request to the /user route:
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
Respond to a DELETE request to the /user route:
app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})
For more details about routing, see the routing guide.
More at http://expressjs.com/en/starter/basic-routing.html

Creating a New Expressjs Project


1. C:\Node4Express>npm install express-generator -g

Response :
C:\Users\User\AppData\Roaming\npm\express -> C:\Users\User\AppData\Roaming\npm\n
ode_modules\express-generator\bin\express
C:\Users\User\AppData\Roaming\npm
`-- express-generator@4.14.1

2. After (1), nothing seems to have been created

C:\Node4Express>dir
 Volume in drive C has no label.
 Volume Serial Number is 5449-2F7F

 Directory of C:\Node4Express

12-Feb-17  06:37 PM    <DIR>          .
12-Feb-17  06:37 PM    <DIR>          ..
12-Feb-17  12:16 PM    <DIR>          helloworld
               0 File(s)              0 bytes
               3 Dir(s)  182,920,482,816 bytes free


3. C:\Node4Express>express --view=pug pms4xpress

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

   install dependencies:
     > cd pms4express && npm install

   run the app:
     > SET DEBUG=pms4express:* & npm start
C:\Node4Express>

4. Verifying what has happened

C:\Node4Express>cd pms4express

C:\Node4Express\pms4express>dir
 Volume in drive C has no label.
 Volume Serial Number is 5449-2F7F

 Directory of C:\Node4Express\pms4express
12-Feb-17  06:46 PM    <DIR>          .
12-Feb-17  06:46 PM    <DIR>          ..
12-Feb-17  06:46 PM             1,256 app.js
12-Feb-17  06:46 PM    <DIR>          bin
12-Feb-17  06:46 PM               336 package.json
12-Feb-17  06:46 PM    <DIR>          public
12-Feb-17  06:46 PM    <DIR>          routes
12-Feb-17  06:46 PM    <DIR>          views
               2 File(s)          1,592 bytes
               6 Dir(s)  182,920,138,752 bytes free



5. Installing dependencies :
C:\Node4Express\pms4xpress>npm install

Response:

pms4express@0.0.0 C:\Node4Express\pms4express
+-- body-parser@1.16.1
| +-- bytes@2.4.0
| +-- content-type@1.0.2
| +-- depd@1.1.0
| +-- http-errors@1.5.1
| | +-- inherits@2.0.3
| | +-- setprototypeof@1.0.2
| | `-- statuses@1.3.1
| +-- iconv-lite@0.4.15
| +-- on-finished@2.3.0
| | `-- ee-first@1.1.1
| +-- qs@6.2.1
| +-- raw-body@2.2.0
| | `-- unpipe@1.0.0
| `-- type-is@1.6.14
|   +-- media-typer@0.3.0
|   `-- mime-types@2.1.14
|     `-- mime-db@1.26.0
+-- cookie-parser@1.4.3
| +-- cookie@0.3.1
| `-- cookie-signature@1.0.6
+-- debug@2.6.1
| `-- ms@0.7.2
+-- express@4.14.1
| +-- accepts@1.3.3
| | `-- negotiator@0.6.1
| +-- array-flatten@1.1.1
| +-- content-disposition@0.5.2
| +-- debug@2.2.0
| | `-- ms@0.7.1
| +-- encodeurl@1.0.1
| +-- escape-html@1.0.3
| +-- etag@1.7.0
| +-- finalhandler@0.5.1
| | `-- debug@2.2.0
| |   `-- ms@0.7.1
| +-- fresh@0.3.0
| +-- merge-descriptors@1.0.1
| +-- methods@1.1.2
| +-- parseurl@1.3.1
| +-- path-to-regexp@0.1.7
| +-- proxy-addr@1.1.3
| | +-- forwarded@0.1.0
| | `-- ipaddr.js@1.2.0
| +-- qs@6.2.0
| +-- range-parser@1.2.0
| +-- send@0.14.2
| | +-- debug@2.2.0
| | | `-- ms@0.7.1
| | +-- destroy@1.0.4
| | `-- mime@1.3.4
| +-- serve-static@1.11.2
| +-- utils-merge@1.0.0
| `-- vary@1.1.0
+-- morgan@1.7.0
| +-- basic-auth@1.0.4
| +-- debug@2.2.0
| | `-- ms@0.7.1
| `-- on-headers@1.0.1
+-- pug@2.0.0-beta11
| +-- pug-code-gen@1.1.1
| | +-- constantinople@3.1.0
| | | +-- acorn@3.3.0
| | | `-- is-expression@2.1.0
| | +-- doctypes@1.1.0
| | +-- js-stringify@1.0.2
| | +-- pug-attrs@2.0.2
| | +-- pug-error@1.3.2
| | +-- void-elements@2.0.1
| | `-- with@5.1.1
| |   `-- acorn-globals@3.1.0
| |     `-- acorn@4.0.11
| +-- pug-filters@2.1.1
| | +-- clean-css@3.4.24
| | | +-- commander@2.8.1
| | | | `-- graceful-readlink@1.0.1
| | | `-- source-map@0.4.4
| | |   `-- amdefine@1.0.1
| | +-- jstransformer@1.0.0
| | | +-- is-promise@2.1.0
| | | `-- promise@7.1.1
| | |   `-- asap@2.0.5
| | +-- pug-walk@1.1.1
| | +-- resolve@1.2.0
| | `-- uglify-js@2.7.5
| |   +-- async@0.2.10
| |   +-- source-map@0.5.6
| |   +-- uglify-to-browserify@1.0.2
| |   `-- yargs@3.10.0
| |     +-- camelcase@1.2.1
| |     +-- cliui@2.1.0
| |     | +-- center-align@0.1.3
| |     | | +-- align-text@0.1.4
| |     | | | +-- kind-of@3.1.0
| |     | | | | `-- is-buffer@1.1.4
| |     | | | +-- longest@1.0.1
| |     | | | `-- repeat-string@1.6.1
| |     | | `-- lazy-cache@1.0.4
| |     | +-- right-align@0.1.3
| |     | `-- wordwrap@0.0.2
| |     +-- decamelize@1.2.0
| |     `-- window-size@0.1.0
| +-- pug-lexer@3.0.0
| | +-- character-parser@2.2.0
| | | `-- is-regex@1.0.3
| | `-- is-expression@3.0.0
| |   `-- acorn@4.0.11
| +-- pug-linker@2.0.2
| +-- pug-load@2.0.5
| | `-- object-assign@4.1.1
| +-- pug-parser@2.0.2
| | `-- token-stream@0.0.1
| +-- pug-runtime@2.0.3
| `-- pug-strip-comments@1.0.2
`-- serve-favicon@2.3.2

6. Verifying what has happened

Response : Node_modules folder created

C:\Node4Express\pms4express>dir
 Volume in drive C has no label.
 Volume Serial Number is 5449-2F7F

 Directory of C:\Node4Express\pms4express

12-Feb-17  06:51 PM    <DIR>          .
12-Feb-17  06:51 PM    <DIR>          ..
12-Feb-17  06:46 PM             1,256 app.js
12-Feb-17  06:46 PM    <DIR>          bin
12-Feb-17  06:51 PM    <DIR>          node_modules
12-Feb-17  06:46 PM               336 package.json
12-Feb-17  06:46 PM    <DIR>          public
12-Feb-17  06:46 PM    <DIR>          routes
12-Feb-17  06:46 PM    <DIR>          views
               2 File(s)          1,592 bytes
               7 Dir(s)  182,905,462,784 bytes free

7. What is inside Node_modules ?



8. C:\Node4Express\pms4xpress>set DEBUG=pms4xpress:* & npm start

C:\Node4Express\pms4express\node_modules>set DEBUG=pms4express:* && npm start

> pms4express@0.0.0 start C:\Node4Express\pms4express
> node ./bin/www

  pms4express:server Listening on port 3000 +0ms

9. localhost:3000


Express Application Generator

Express application generator

Use the application generator tool, express-generator, to quickly create an application skeleton.
The express-generator package installs the express command-line tool. Use the following command to do so:
$ npm install express-generator -g
Display the command options with the -h option:
$ express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
        --version       output the version number
    -e, --ejs           add ejs engine support
        --hbs           add handlebars engine support
        --pug           add pug engine support
    -H, --hogan         add hogan.js engine support
    -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory
For example, the following creates an Express app named myapp in the current working directory:
$ express --view=jade myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.jade
   create : myapp/views/layout.jade
   create : myapp/views/error.jade
   create : myapp/bin
   create : myapp/bin/www
Then install dependencies:
$ cd myapp
$ npm install
On MacOS or Linux, run the app with this command:
$ DEBUG=myapp:* npm start
On Windows, use this command:
> set DEBUG=myapp:* & npm start
Then load http://localhost:3000/ in your browser to access the app.
The generated app has the following directory structure:
.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

7 directories, 9 files
The app structure created by the generator is just one of many ways to structure Express apps. Feel free to use this structure or modify it to best suit your needs.
More at http://expressjs.com/en/starter/generator.html