Node Js

Node js Help for

  • File Handling
  • Create or Remove file from hard disk
  • Connect DB
  • Perform Query

V8 Engine converts java script syntax code to machine understand language

Chrome browser <-> V8 Engine written by C++

Chrome browser and node are similar, so that it prints the same response in terminal and browser following command

console.log(“Hello world!”)

Chrome have window, node have global

Chrome have document, node have proess

Enter to node -> node

Exit from node -> processs.exit(0);

Node js uses an event-driven, non blocking I/O model that makes it lightweight and efficient.

npmjs.com helps download packages

 

Require function

It is help for include the package in the project.

Example(Index.js)

console.log(“Hello world”);

const fs = require(“fs”);// File system

const os = require(“os”)//OS Information

const notes = require(‘./notes’)

var user = os.userInfo();

//fs.appendFile(“message.txt”,”Hello “+user.username)

fs.appendFile(“message.txt”,`Hello ${user.username}  you are ${notes.age} old`)

var res = notes.addNote();

console.log(res)// Note created

var addres = notes.add(5,2);

console.log(addres)// 7

Example(notes.js)

console.log(“This is notes”);

console.log(module);

module.exports.age = 29

//ES 5 function syntax

module.exports.addNoteold = function(){

}

//ES 6 function syntax

module.exports.addNote = () => {

console.log(‘Add note called’)

return ‘Note created’

}

module.exports.add = (a,b) => {

return a+b;

}

Check npm version

npm -v

create project

npm init  // It creates the project, with package.json

npm init -y // Creates project directly.

install new package in the project

npm install lodash — save

While sharing the project we can delete node module, it is the folder downloaded packages from the cloud. So that we can download the packages using npm install for the new workspace. [node module have project dependencies]

nodemon library helps avoid multiple time restart, while development, It is a global library to utilise all the project

npm install nodemon -g

lodash library helps access the utilities quick access.

Require function first checks core libraries like os, fs then if it is not there it checks the node_modules.

const _= require(‘lodash’)

console.log(_.isString(‘abc’));// return boolean

console.log(_.uniq([2,1,3,2]));// return [2,1,3]

Command line arguments

Example(index.js)// node index.js [command] — title=’Note1′

console.log(process.argv);

var command = process.argv[2];

if(command === ‘list’){

console.log(‘list all notes’)

}

else if(command === ‘read’){

console.log(‘Read Note’)

}

else if(command === ‘create’){

console.log(‘Note Created’)

}

else if(command === ‘remove’){

console.log(‘Note Removed’)

}

else {

console.log(‘Command not found’)

}

 

command line argument is not user friendly, so that we have to install yargs library

npm install yargs –save

 

Example(index.js) // node index.js [command] {arg1,arg2}

console.log(process.argv);

const notes = require(‘notes’)

const yargs = require(‘yargs’)

//var command = process.argv[2];

var argv = yargs.argv

var command = argv._[0]

if(command === ‘list’){

console.log(‘list all notes’)

notes.getAllNotes();

}

else if(command === ‘read’){

console.log(‘Read Note’)

notes.readNote(argv.title);

}

else if(command === ‘create’){

console.log(‘Note Created’)

notes.createNote(argv.title,argv.body);

}

else if(command === ‘remove’){

console.log(‘Note Removed’)

notes.removeNote(argv.title);

}

else {

console.log(‘Command not found’)

}

Example(notes.js)

var createNote = (title,body) => {

console.log(“Note Created”)

}

var getAllNotes = ()=>{

console.log(“Get all notes”)

}

 

var readNote = (title)=>{

console.log(“Read note “,title)

}

var removeNote = (title)=>{

console.log(“Remove note “,title)

}

modules.export = {

//createNote  : createNote

createNote  // In ES 6 if Key and Value are same, Note require to give the value

getAllNotes

readNote

removeNote

}

Debug

node –inspect-brk index.js create –title =”New note” –body = “content”

Call stack and call back

Express Framework

Express helps for creating the route

npm install express –save

Example(index.js)

const express = require(‘express’);
var app = express();

app.get(‘/’,(req,res) =>{
res.send(‘welcome’);
});

app.get(‘/about’,(req,res)=>{
res.send(‘about’);
});

app.listen(3000);// 0 to 65536

Static files configuring

By default we can’t access the static files from the server, so that we need to configure using express library as follows,

app.use(express.static(‘public’));// public is root folder have all asset files. it is the middleware

View Engine

res.send() always send the string, If we want to pass the page we need to install ejs library.

npm install ejs –save

 

const express = require(‘express’);
var app = express();

app.set(‘view engine’,’ejs’);// This server view engine working for ejs mode

app.get(‘/’,(req,res) =>{
//res.send(‘welcome’);

res.render(‘home’);//here home consider as the home.ejs file, We should  create a folder with the name of  views. ejs files similar to html.
});

app.get(‘/about’,(req,res)=>{
res.send(‘about’);
});

app.listen(3000);// 0 to 65536

Server side rendering

Client Request -> Application Server->Database Server

After collecting the data, application server return to the client as html.

Client side rendering

Client Request <-> Application Server (Application server returns the html layout behaviours)

Again client request the data <-> Application server<->Database server

After receiving the data client place the values for the layout behaviours.

Return the json in the routing

const express = require(‘express’);
var app = express();

app.set(‘view engine’,’ejs’);// This server view engine working for ejs mode

app.get(‘/api’,(req,res) => {

res.json({

name: “hello”

})

})

app.listen(3000);

include 

include helps for adding the contents partially, so that we can remove the  same content in all files.

<%- include(‘content.ejs’) %>

Pass Data into views

Example(index.js)

app.get(‘/products’,(req,res) => {

res.render(‘products’,{

title: “Pass pass”

})

})

Example(product.js)

<%= title%>

URL Parameters

www.hello.com/product/1=> here product is the route and 1 is the id

app.get(‘/product/:id’,(req,res) =>{// id coming from req variable

console.log(req.params.id);

var data = [{

id:1,

productName:”One”

},

{

id:2,

productName:”Two”

}]

var result;

data.forEach((product) => {

if(product.id == req.params.id)

{

result = product;

return true;

}

})

res.render(‘details,’,{

title:”Product details”,

product:result

})

})

(Example details.js)

<% = product.productName %>