Friday, January 12, 2018

Introduction to Node

Node.js

Node.js is an open-source, cross-platform, JavaScript runtime built on Chrome's V8 Javascript engine that allows developers to create all kinds of server-side tools and applications in JavaScript. Node.js was developed by Ryan Dahl in 2009.
https://nodejs.org/en/
  • Javascript everywhere
  • Great performance
  • Asynchronous and event driven
  • Single threaded
  • Node package manager (npm) provides access to thousands of reusable packages.
  • Portable

Express

Express is an un-opinionated, minimalist web framework for Node.js
https://expressjs.com/

Setting up the Node environment

  • Install Node
  • $ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
    $ sudo apt-get install -y nodejs
    $ node -v
  • Install express generator
  • The express application generator tool generates an Express application skeleton.
    $ npm install express-generator -g
    (-g flag installs the tool globally)
  • Create skeleton project
  • $ express --ejs --git hellonode
    $ cd hellonode
    $ npm install
    $  DEBUG=hellonode:* npm start
    then go to browser and enter http://localhost:3000/
  • Enable server restart on file changes
  • $ npm install --save-dev nodemon
    then update the scripts section as below,
    "scripts": {
        "start": "node ./bin/www",
        "devstart": "nodemon ./bin/www"
      },

    $ npm run devstart
  • Directory structure
  • Let's have a look at the generated files.
    >> package.json
    defines the application dependencies and other information

    express: express framework

    body-parser: parses the body portion of an incoming HTTP request and makes it easier to extract different parts of the contained information.

    cookie-parser: uses to parse the cookie  header.

    morgan: HTTP request logger

    ejs: view template engine

    nodemon: enable server restart

    >> www file
    application entry point

    >> app.js
    sets up the application with various settings and middlewares.

    >> routes
    routers

    >> views
    view templates

Congratulations!!! you just created your first website which runs using Node!!!


No comments:

Post a Comment