NodeJS

What is express js and why it is used?
Express.js is a modular web framework for Node.js. It is used for easier creation of web applications and services. Express.js simplifies development and makes it easier to write secure, modular and fast applications.







JWT Token - Node Js
https://github.com/auth0/node-jsonwebtoken



Issue resolve of request.body parameter value using    openapi: '3.0.1',
https://stackoverflow.com/questions/58634566/swagger-openapi-3-0-x-empty-body

Refrenece:
https://medium.com/javascript-in-plain-english/typescript-with-node-and-express-js-why-when-and-how-eb6bc73edd5d

Node js with Types Script


. npm init  -- to create package.json

2. npm install typescript -s

include  in package.json

"scripts": {
"tsc": "tsc"
},

3. npm run tsc -- --init  -- to create tsconfig.json

4. npm install express -s

5. npm install @types/express -s

6. Create app/app.ts
7. npm run tsc
8. Running the express
     node build/app.js
import express = require('express');

// Create a new express application instance
const app: express.Application = express();

app.get('/'function (req, res) {
  res.send('Hello gueru World!');
});

app.listen(3000function () {
  console.log('Example app listening on port 3000!');
});


9. npm install ts-node-dev -s

10. update package.json

"scripts": {
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./app/app.ts",
"prod": "tsc && node ./build/app.js"
},

To start the development environment:
npm run dev
To run the server in production mode:
npm run prod



Step Node js configuration

1. Install node js on machine

2. Install type script 

3. Install Express server  --express Project Directory

4. npm install cors 

5.npm install mssql

6. npm install connect-- for middle ware (app.use)
7 npm install tedious for sql server driver

Package .json


{
  "name""erpapp",
  "version""0.0.0",
  "private"true,
  "scripts": {
    "start""node ./bin/www"
  },
  "dependencies": {
    "body-parser""1.8",
    "connect""^3.7.0",
    "cookie-parser""~1.4.4",
    "cors""^2.8.5",
    "debug""~2.6.9",
    "express""~4.16.1",
    "express-favicon""^2.0.1",
    "http-errors""~1.6.3",
    "jade""~1.11.0",
    "method-override""*",
    "morgan""~1.9.1",
    "mssql""^6.2.0",
    "pug""^2.0.4",
    "stylus""^0.54.7",
    "tedious""^8.3.0"
  }
}



Sql Db Configuration:

var dbConfig = {
    user'sa',
    password'sa12345',
    server'DESKTOP-DG3KLUB'
    database'ERP',
    port1433,
    dialect:"ssql",       
    options:{
      enableArithAbort:true
    },
    "dialect""mssql",
"dialectOptions": {
    "instanceName""MSQLSERVER"
}
};












Installation:
https://nodejs.org/en/download

Windows Installer


https://www.edureka.co/blog/typescript-tutorial/



Type Script with Node js Configuration.

https://developer.okta.com/blog/2018/11/15/node-express-typescript


Node Js in visual studio https://docs.microsoft.com/en-us/visualstudio/javascript/tutorial-nodejs?view=vs-2019



CallBack Function: What is Callback?
What is a Callback?

Synchronous vs Asynchronous. The send, receive, and reply operations may be synchronous or asynchronous
  1. Node.js is an open-source framework under MIT license. (MIT license is a free software license originating at the Massachusetts Institute of Technology (MIT).)
  1. Uses JavaScript to build entire server side application.
  1. Lightweight framework that includes bare minimum modules. Other modules can be included as per the need of an application.
  1. Asynchronous by default. So it performs faster than other frameworks.
  1. Cross-platform framework that runs on Windows, MAC or Linux
  1. Node.js
  1. Node Package Manager (NPM)
  1. IDE (Integrated Development Environment) or TextEditor -Visual Studio, Sublime text, Eclipse, Aptana
  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • RegExp
},
}
},
}
Node.js Module Types
  1. Core Modules
  1. Local Modules
  1. Third Party Modules
Node.js Core Modules
Core Module
Description
http module includes classes, methods and events to create Node.js http server.
url module includes methods for URL resolution and parsing.
querystring module includes methods to deal with query string.
path module includes methods to deal with file paths.
fs module includes classes, methods, and events to work with file I/O.
util module includes utility functions useful for programmers.
Node.js Local Module:
Node.js Local Module:
info: function (info) {

console.log('Info: ' + info);

},

warning:function (warning) {

console.log('Warning: ' + warning);

},

error:function (error) {

console.log('Error: ' + error);

}
};
module.exports = log

console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log
};
};
Loading Local Module:
Reference:https://www.tutorialsteacher.com/nodejs/nodejs-module-exports
Export Literals:
module.exports = 'Hello world';
Export Object:
exports.SimpleMessage = 'Hello world';
Load Module from Separate Folder:
var log = require('./utility/log.js');
 you can specify only utility folder without specifing log.js
var log = require('./utility');
utility folder. This is because Node assumes that this folder is a
Reference: https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server

Example: Open File 
return console.error(err);

}
Delete File
Method
Description
fs.readFile(fileName [,options], callback)
Reads existing file.
fs.writeFile(filename, data[, options], callback)
Writes to the file. If file exists then overwrite the content otherwise creates new file.
fs.open(path, flags[, mode], callback)
Opens file for reading or writing.
fs.rename(oldPath, newPath, callback)
Renames an existing file.
fs.chown(path, uid, gid, callback)
Asynchronous chown.
fs.stat(path, callback)
Returns fs.stat object which includes important file statistics.
fs.link(srcpath, dstpath, callback)
Links file asynchronously.
fs.symlink(destination, path[, type], callback)
Symlink asynchronously.
fs.rmdir(path, callback)
Renames an existing directory.
fs.mkdir(path[, mode], callback)
Creates a new directory.
fs.readdir(path, callback)
Reads the content of the specified directory.
fs.utimes(path, atime, mtime, callback)
Changes the timestamp of the file.
fs.exists(path, callback)
Determines whether the specified file exists or not.
fs.access(path[, mode], callback)
Tests a user's permissions for the specified file.
fs.appendFile(file, data[, options], callback)
Appends new content to the existing file.

console: function(msg) {

console.log(msg);

file: function(msg) {

// log to file here

}


application.each module can be placed in a separate .js file under a

separate folder.

Node.js includes three types of modules:

Node.js is a light weight framework. The core modules include bare minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts.

Loading Core Modules:

you first need to import it using require() function as shown below.
var module = require('module_name');
var http = require('http');
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);
Local modules are modules created locally in your Node.js application.
These modules include different functionalities of your application
in separate files and folders which can be reused in your application.
Example:
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
module.exports = log
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
module.exports = log
The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.
myLogModule.info('Node.js started');
exports is an object. So it exposes whatever you assigned to it as a module.
var msg = require('./Messages.js');
console.log(msg);
console.log(msg);
var msg = require('./Messages.js');
console.log(msg.SimpleMessage);
console.log(msg.SimpleMessage);
 you can expose an object with function.
console.log(msg);
};
var msg = require('./Log.js');
msg.log('Hello World');
msg.log('Hello World');
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
firstName: 'James',
lastName: 'Bond'
}
var person = require('./data.js');
console.log(person.firstName + ' ' + person.lastName);
console.log(person.firstName + ' ' + person.lastName);
But in this case

Node will search for a package definition file called package.json inside

package.json file should be in a module directory. The package.json

key as below. package.json file
{
"name" : "log",
"main" : "./log.js"
}
"name" : "log",
"main" : "./log.js"
}
If package.json file does not exist then it will look for index.js file

as a module file by default.
server.js
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 - creating server
//handle incomming requests here..
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
var server = http.createServer(function (req, res) { // 2 - creating server
//handle incomming requests here..
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
Run the above web server by writing node server.js command in command prompt or terminal window and it will display message as shown below.
Node.js web server at port 5000 is running..














fs.open('TestFile.txt', 'r', function (err, fd) {
if (err) {
return console.error(err);
}

if (err) {

return console.error(err);

}


Use fs.unlink() method to delete an existing file.


Method
Description
fs.readFile(fileName [,options], callback)
Reads existing file.
fs.writeFile(filename, data[, options], callback)
Writes to the file. If file exists then overwrite the content otherwise creates new file.
fs.open(path, flags[, mode], callback)
Opens file for reading or writing.
fs.rename(oldPath, newPath, callback)
Renames an existing file.
fs.chown(path, uid, gid, callback)
Asynchronous chown.
fs.stat(path, callback)
Returns fs.stat object which includes important file statistics.
fs.link(srcpath, dstpath, callback)
Links file asynchronously.
fs.symlink(destination, path[, type], callback)
Symlink asynchronously.
fs.rmdir(path, callback)
Renames an existing directory.
fs.mkdir(path[, mode], callback)
Creates a new directory.
fs.readdir(path, callback)
Reads the content of the specified directory.
fs.utimes(path, atime, mtime, callback)
Changes the timestamp of the file.
fs.exists(path, callback)
Determines whether the specified file exists or not.
fs.access(path[, mode], callback)
Tests a user's permissions for the specified file.
fs.appendFile(file, data[, options], callback)
Appends new content to the existing file.
Debug Node.js Application:
It provides different commands for debugging Node.js application.
Consider the following simple Node.js application contained in app.js file.
app.js
fs.readFile('test.txt', 'utf8', function (err, data) {
debugger;
if (err) throw err;
console.log(data);
});
Command
Description
next
Stop at the next statement.
cont
Continue execute and stop at the debugger statement if any.
step
Step in function.
out
Step out of function.
watch
Add the expression or variable into watch.
watcher
See the value of all expressions and variables added into watch.
Pause
Pause running code.


A synchronous operation blocks a process till the operation completes.
The notion of synchronous operations requires an understanding of what it means for an operation to complete. In the case of remote assignment, both the send and receive complete when the message has been delivered to the receiver. In the case of remote procedure call, the send, receive, and reply complete when the result has been delivered to the sender, assuming there is a return value. Otherwise, the send and receive complete when the procedure finishes execution. During the time the procedure is executing, the sender and receiver are in a rendezvous, as mentioned before.
Asynchronous message passing allows more parallelism. Since a process does not block, it can do some computation while the message is in transit. In the case of receive, this means a process can express its interest in receiving messages on multiple ports simultaneously. (The select primitive discussed later provides this facility for synchronous receives). In a synchronous system, such parallelism can be achieved by forking a separate process for each concurrent operation, but this approach incurs the cost of extra process management.
Node Package Manager:
Install Package Locally:
Advantages of Node.js
Setup Node.js Development Environment:
Verify Installation:
Node.js Console:REPL
Node.js Basics:
Primitive Types
Loose Typing
Functions
Buffer
Process object
Defaults to local:
Access Global Scope
console.log(msg);

file: function(msg) {

// log to file here

}

// log to file here

Now, you can import log object using require() function and use it anywhere
in your Node.js project.
Node.js Module:


application.each module can be placed in a separate .js file under a











you first need to import it using require() function as shown below.



var module = require('module_name');



var http = require('http');
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);

//write code here

});

server.listen(5000);
Local modules are modules created locally in your Node.js application.
These modules include different functionalities of your application
in separate files and folders which can be reused in your application.
Example:
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
module.exports = log
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
module.exports = log
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
module.exports = log
The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.
console.log(msg);
};
};
firstName: 'James',
lastName: 'Bond'
}
lastName: 'Bond'
}
console.log(person.firstName + ' ' + person.lastName);

package and will try to look for a package definition. The
under utility folder specifies the file name using "main"

"name" : "log",

"main" : "./log.js"

}

"main" : "./log.js"

}



Node.js Web Server:





//handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')



Node.js File System
Example: Reading File
var fs = require('fs');
fs.readFile('TestFile.txt', function (err, data) {
                    if (err) throw err;
    console.log(data);});
Example: Reading File Synchronously
var fs = require('fs');
var data = fs.readFileSync('dummyfile.txt', 'utf8');

Example: Creating & Writing File
 var fs = require('fs');
 fs.writeFile('test.txt', 'Hello World!', function (err) 
{ if (err) console.log(err); else console.log('Write operation complete.'); });
Example: Append File Content 
var fs = require('fs'); 
 fs.appendFile('test.txt', 'Hello World!', function (err) { if (err) console.log(err); else console.log('Append operation complete.'); });
Example: Open File 
fs.open('TestFile.txt', 'r', function (err, fd) {
if (err) {
return console.error(err);
}
return console.error(err);

}

Delete File
Use fs.unlink() method to delete an existing file.



Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.
References:


More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function.


An asynchronous operation is non-blocking and only initiates the operation.


Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls Node.js packages in your application. It is also an online repository for open-source Node.js packages. The node community around the world creates useful modules and publishes them as packages in this repository.
Official website: https://www.npmjs.com
C:\>npm install <package name>

For example, the following command will install ExpressJS into MyNodeProj folder.

C:\MyNodeProj> npm install express

Add Dependency into package.json

C:\MyNodeProj> npm install express  --save
 // Use save the end of the command.


Install Package Globally :
NPM installs global packages into /<User>/local/lib/node_modules folder.

C:\MyNodeProj> npm install -g express


Update Package:



C:\MyNodeProj> npm update <package name>

The following command will update the existing ExpressJS module to the latest version.



C:\MyNodeProj> npm update express

Uninstall Packages:

Use the following command to remove a local package from your project.



C:\>npm uninstall <package name>


Node.js:



Node.js is an open-source server side runtime environment built on Chrome's V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.
Node.js was written and introduced by Ryan Dahl in 2009.


The V8 Engine which is built by Google is open source and written in C++. This engine is used inside Google Chrome. Unlike the rest of the engines, however, V8 is also used for the popular Node.js runtime. V8 was first designed to increase the performance of JavaScript execution inside web browsers



Node.js can be used to build different types of applications such as command line application, web application, real-time chat application, REST API server etc. However, it is mainly used to build network programs like web servers, similar to PHP, Java, or ASP.NET.
Disadvantages:
Node.js is not fit for an application which performs CPU-intensive operations like image processing or other heavy computation work because it takes time to process a request and thereby blocks the single thread.



Node Js Event Loop Process:









Node.js development environment can be setup in Windows, Mac, Linux and Solaris.

NPM (Node Package Manager).



Visit Node.js official web site https://nodejs.org. It will automatically detect OS and display download link as per your Operating System. For example, it will display following download link for 64 bit Windows OS.
you can verify it by opening the command prompt and typing node -v. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine.

Type Node in Command Prompt
c:>node

Node.js includes following primitive types:
Everything else is an object in Node.js.
JavaScript in Node.js supports loose typing like the browser's JavaScript. Use var keyword to declare a variable of any type.
Object Example:
var obj = {    authorName: 'Ryan Dahl',    language: 'Node.js'}

Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript.
 function Display(x) {     console.log(x);}
Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.
Each Node.js script runs in a process. It includes process object to get all the information about the current process of Node.js application.
In the browser's JavaScript, variables declared without var keyword become global. In Node.js, everything becomes local by default.

In a browser, global scope is the window object. In Node.js, global object represents the global scope.To add something in global scope, you need to export it using export or module.export. The same way, import modules/object using require() function to access it from the global scope.
exports.log = {
console: function(msg) {
console.log(msg);
file: function(msg) {
// log to file here
}
Module in Node.js is a simple or complex functionality organized in single

or multiple JavaScript files which can be reused throughout the Node.js
application.each module can be placed in a separate .js file under a
separate folder.
Node.js includes three types of modules:
Node.js is a light weight framework. The core modules include bare minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts.

Loading Core Modules:

you first need to import it using require() function as shown below.
var module = require('module_name');
var http = require('http');
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);
Local modules are modules created locally in your Node.js application.
These modules include different functionalities of your application
in separate files and folders which can be reused in your application.
Example:
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
module.exports = log
The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.
var myLogModule = require('./Log.js');
myLogModule.info('Node.js started');
exports is an object. So it exposes whatever you assigned to it as a module.
var msg = require('./Messages.js');
console.log(msg);
var msg = require('./Messages.js');
console.log(msg.SimpleMessage);
 you can expose an object with function.
module.exports.log = function (msg) {
console.log(msg);
};
var msg = require('./Log.js');
msg.log('Hello World');
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
var person = require('./data.js');
console.log(person.firstName + ' ' + person.lastName);
But in this case

Node will search for a package definition file called package.json inside

package.json file should be in a module directory. The package.json

key as below. package.json file
{
"name" : "log",
"main" : "./log.js"
}
If package.json file does not exist then it will look for index.js file

as a module file by default.
Node.js provides capabilities to create your own web server which will handle HTTP requests asynchronously. You can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web server.
server.js
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 - creating server
//handle incomming requests here..
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
Run the above web server by writing node server.js command in command prompt or terminal window and it will display message as shown below.
C:\> node server.js 
Node.js web server at port 5000 is running..

Node.js includes fs module to access physical file system. The fs module is responsible for all the asynchronous or synchronous file I/O operations.
Example: Reading File
var fs = require('fs');
fs.readFile('TestFile.txt', function (err, data) {
                    if (err) throw err;
    console.log(data);});
Example: Reading File Synchronously
var fs = require('fs');
var data = fs.readFileSync('dummyfile.txt', 'utf8');
console.log(data);
Example: Creating & Writing File
 var fs = require('fs');
 fs.writeFile('test.txt', 'Hello World!', function (err) 
{ if (err) console.log(err); else console.log('Write operation complete.'); });
Example: Append File Content 
var fs = require('fs'); 
 fs.appendFile('test.txt', 'Hello World!', function (err) { if (err) console.log(err); else console.log('Append operation complete.'); });
fs.open('TestFile.txt', 'r', function (err, fd) {
if (err) {
return console.error(err);
}
Use fs.unlink() method to delete an existing file.
Command
Description
next
Stop at the next statement.
cont
Continue execute and stop at the debugger statement if any.
step
Step in function.
out
Step out of function.
watch
Add the expression or variable into watch.
watcher
See the value of all expressions and variables added into watch.
Pause
Pause running code.
Command
Description
next
Stop at the next statement.
cont
Continue execute and stop at the debugger statement if any.
step
Step in function.
out
Step out of function.
watch
Add the expression or variable into watch.
watcher
See the value of all expressions and variables added into watch.
Pause
Pause running code.

Node Inspector:

Node Inspector: Node Inspector:
Node inspector is GUI based debugger. Install Node Inspector using NPM in the global
mode by writing the following command in the terminal window (in Mac or Linux) or
npm install -g node-inspector

command prompt (in Windows).
events. var em = new emitter(); //Subscribe FirstEvent console.log('First subscriber: ' + data); //Subscribe SecondEvent em.on('SecondEvent', function (data) { }); // Raising FirstEvent // Raising SecondEvent em.emit('SecondEvent', 'This is my second Node.js event emitter example.'); Frameworks for Node.js:
Open-Source Framework
Description
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. This is the most popular framework as of now for Node.js.
Geddy is a simple, structured web application framework for Node.js based on MVC architecture.
Locomotive is MVC web application framework for Node.js. It supports MVC patterns, RESTful routes, and convention over configuration, while integrating seamlessly with any database and template engine. Locomotive builds on Express, preserving the power and simplicity you've come to expect from Node.
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
Totaljs is free web application framework for building web sites and web applications using JavaScript, HTML and CSS on Node.js
Hapi is a rich Node.js framework for building applications and services.
Keystone is the open source framework for developing database-driven websites, applications and APIs in Node.js. Built on Express and MongoDB.
Derby support single-page apps that have a full MVC structure, including a model provided by Racer, a template and styles based view, and controller code with application logic and routes.
Sails makes it easy to build custom, enterprise-grade Node.js apps. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture. It's especially good for building chat, realtime dashboards, or multiplayer games; but you can use it for any web application project - top to bottom.
Meteor is a complete open source platform for building web and mobile apps in pure JavaScript.
This HTML5 framework for the browser and server from Yahoo offers direct MVC access to the server database through the local routines. One clever feature allows the code to migrate. If the client can't run JavaScript for some reason, Mojito will run it on the server -- a convenient way to handle very thin clients.
Restify is a node.js module built specifically to enable you to build correct REST web services.
Loopback is an open-source Node.js API framework.
actionhero.js is a multi-transport Node.JS API Server with integrated cluster capabilities and delayed tasks.
Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun.
Core Node.js Debugger

Node.js provides built-in non-graphic debugging tool that can be used on all platforms.

var fs = require('fs');

node debug app.js

Run the command
Node inspector is GUI based debugger. Install Node Inspector using NPM in the global
mode by writing the following command in the terminal window (in Mac or Linux) or
npm install -g node-inspector

command prompt (in Windows).
start the node inspector on a different port using the following command.

D:\>node-inspector --web-port=5500
Node.js EventEmitter :
Node.js allows us to create and handle custom events easily by using events module.
Event module includes EventEmitter class which can be used to raise and handle custom
Open-Source Framework
Description
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. This is the most popular framework as of now for Node.js.
Geddy is a simple, structured web application framework for Node.js based on MVC architecture.
Locomotive is MVC web application framework for Node.js. It supports MVC patterns, RESTful routes, and convention over configuration, while integrating seamlessly with any database and template engine. Locomotive builds on Express, preserving the power and simplicity you've come to expect from Node.
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
Totaljs is free web application framework for building web sites and web applications using JavaScript, HTML and CSS on Node.js
Hapi is a rich Node.js framework for building applications and services.
Keystone is the open source framework for developing database-driven websites, applications and APIs in Node.js. Built on Express and MongoDB.
Derby support single-page apps that have a full MVC structure, including a model provided by Racer, a template and styles based view, and controller code with application logic and routes.
Sails makes it easy to build custom, enterprise-grade Node.js apps. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture. It's especially good for building chat, realtime dashboards, or multiplayer games; but you can use it for any web application project - top to bottom.
Meteor is a complete open source platform for building web and mobile apps in pure JavaScript.
This HTML5 framework for the browser and server from Yahoo offers direct MVC access to the server database through the local routines. One clever feature allows the code to migrate. If the client can't run JavaScript for some reason, Mojito will run it on the server -- a convenient way to handle very thin clients.
Restify is a node.js module built specifically to enable you to build correct REST web services.
Loopback is an open-source Node.js API framework.
actionhero.js is a multi-transport Node.JS API Server with integrated cluster capabilities and delayed tasks.
Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun.
Node inspector is GUI based debugger. Install Node Inspector using NPM in the global
mode by writing the following command in the terminal window (in Mac or Linux) or
npm install -g node-inspector

command prompt (in Windows).
Node.js EventEmitter :
Node.js allows us to create and handle custom events easily by using events module.
Event module includes EventEmitter class which can be used to raise and handle custom
var emitter = require('events').EventEmitter;
em.addListener('FirstEvent', function (data) {
});
console.log('First subscriber: ' + data);
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
Open-Source Framework
Description
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. This is the most popular framework as of now for Node.js.
Geddy is a simple, structured web application framework for Node.js based on MVC architecture.
Locomotive is MVC web application framework for Node.js. It supports MVC patterns, RESTful routes, and convention over configuration, while integrating seamlessly with any database and template engine. Locomotive builds on Express, preserving the power and simplicity you've come to expect from Node.
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
Totaljs is free web application framework for building web sites and web applications using JavaScript, HTML and CSS on Node.js
Hapi is a rich Node.js framework for building applications and services.
Keystone is the open source framework for developing database-driven websites, applications and APIs in Node.js. Built on Express and MongoDB.
Derby support single-page apps that have a full MVC structure, including a model provided by Racer, a template and styles based view, and controller code with application logic and routes.
Sails makes it easy to build custom, enterprise-grade Node.js apps. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture. It's especially good for building chat, realtime dashboards, or multiplayer games; but you can use it for any web application project - top to bottom.
Meteor is a complete open source platform for building web and mobile apps in pure JavaScript.
This HTML5 framework for the browser and server from Yahoo offers direct MVC access to the server database through the local routines. One clever feature allows the code to migrate. If the client can't run JavaScript for some reason, Mojito will run it on the server -- a convenient way to handle very thin clients.
Restify is a node.js module built specifically to enable you to build correct REST web services.
Loopback is an open-source Node.js API framework.
actionhero.js is a multi-transport Node.JS API Server with integrated cluster capabilities and delayed tasks.
Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun.

Express.js:

Express.js: Express.js:
Express.js is a web application framework for Node.js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.js.
Advantages of Express.js Advantages of Express.js
  1. Makes Node.js web application development fast and easy.
  2. Easy to configure and customize.
  3. Allows you to define routes of your application based on HTTP methods and URLs.
  4. Includes various middleware modules which you can use to perform additional tasks on request and response.
  5. Easy to integrate with different template engines like Jade, Vash, EJS etc.
  6. Allows you to define an error handling middleware.
  7. Easy to serve static files and resources of your application.
  8. Allows you to create REST API server.
  9. Easy to connect with databases such as MongoDB, Redis, MySQL
  1. Makes Node.js web application development fast and easy.
  1. Easy to configure and customize.
  1. Allows you to define routes of your application based on HTTP methods and URLs.
  1. Includes various middleware modules which you can use to perform additional tasks on request and response.
  1. Easy to integrate with different template engines like Jade, Vash, EJS etc.
  1. Allows you to define an error handling middleware.
  1. Easy to serve static files and resources of your application.
  1. Allows you to create REST API server.
  1. Easy to connect with databases such as MongoDB, Redis, MySQL
  1. Makes Node.js web application development fast and easy.
  1. Makes Node.js web application development fast and easy.
  1. Easy to configure and customize.
  1. Easy to configure and customize.
  1. Allows you to define routes of your application based on HTTP methods and URLs.
  1. Allows you to define routes of your application based on HTTP methods and URLs.
  1. Includes various middleware modules which you can use to perform additional tasks on request and response.
  1. Includes various middleware modules which you can use to perform additional tasks on request and response.
  1. Easy to integrate with different template engines like Jade, Vash, EJS etc.
  1. Easy to integrate with different template engines like Jade, Vash, EJS etc.
  1. Allows you to define an error handling middleware.
  1. Allows you to define an error handling middleware.
  1. Easy to serve static files and resources of your application.
  1. Easy to serve static files and resources of your application.
  1. Allows you to create REST API server.
  1. Allows you to create REST API server.
  1. Easy to connect with databases such as MongoDB, Redis, MySQL
  1. Easy to connect with databases such as MongoDB, Redis, MySQL
Serving Static Resources in Node.js: Serving Static Resources in Node.js:
serve static resources like images, css, JavaScript or other static files using Express.js and node-static module.
Serve Static Resources using Express.js:
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public'));
app.use(express.static(__dirname + 'public'));
app.use(express.static(__dirname + 'public'));
var server = app.listen(5000);
In above example app.use() method mounts the middle ware In above example app.use() method mounts the middle ware
express.static for every request.
express.static for every request. express.static for every request.
var express = require('express');
var app = express();
app.use(express.static('public'));
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
//Serves all the request which includes /images in the url from Images folder
Serve Static Resources using Node-static Module: Serve Static Resources using Node-static Module:
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5000);
Data Access in Node.js: Data Access in Node.js:
Node.js supports all kinds of databases no matter if it is a relational database or NoSQL database. However, NoSQL databases like MongoDb are the best fit with Node.js.
Relational Databases
Driver
NPM Command
MS SQL Server
npm install mssql
Oracle
npm install oracledb
MySQL
npm install mysql
PostgreSQL
npm install pg
SQLite
npm install node-sqlite
Express.js is a web application framework for Node.js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.js.
serve static resources like images, css, JavaScript or other static files using Express.js and node-static module.
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public'));
var server = app.listen(5000);
var app = express();
app.use(express.static('public'));
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
 app.use() method mounts the express.static middle ware for every request that starts with "/images". It will serve images from images folder for every HTTP requests that starts with "/images".
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5000);
Relational Databases
Driver
NPM Command
MS SQL Server
npm install mssql
Oracle
npm install oracledb
MySQL
npm install mysql
PostgreSQL
npm install pg
SQLite
npm install node-sqlite
To access the database from Node.js, you first need to install drivers for the database you want to use.
Access SQL Server in Node.js: Access SQL Server in Node.js:
Install mssql driver using npm command, npm install mssql in the command prompt. This will add mssql module folder in node_modules folder in your Node.js application
var express = require('express'); var app = express(); }); }); }); Template Engines for Node.js: Template Engines for Node.js:
Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.The following figure illustrates how template engine works in Node.js.
Advantages of Template engine in Node.js
  1. Improves developer's productivity.
  1. Improves readability and maintainability.
  1. Improves readability and maintainability.
  1. Faster performance.
  1. Faster performance.
  1. Maximizes client side processing.
  1. Maximizes client side processing.
  1. Single template for multiple pages.
  1. Single template for multiple pages.
  1. Templates can be accessed from CDN (Content Delivery Network).
  1. Templates can be accessed from CDN (Content Delivery Network).
Jade Template Engine: Jade Template Engine:
Jade is a template engine for Node.js. Jade syntax is easy to learn.
It uses white space and indentation as a part of the syntax.
Jade template must be written inside .jade file.
Install jade into your project using NPM as below. npm install jade
And all .jade files must be put inside views folder in the root folder of
Install jade into your project using NPM as below. npm install jade Install jade into your project using NPM as below. npm install jade
Sample.jade
Sample.jade Sample.jade
doctype html
html
title Jade Page
head
h1 This page is produced by Jade engine
body
p some paragraph here..
html head body html head body
app.set("view engine","jade")
Jade Tutorial Jade Tutorial Reference:https://webapplog.com/jade/ Jade Syntax and Features: Tags: Any text at the beginning of a line—by default—is interpreted as an HTML tag.  div Variables/Locals: Variables/Locals:
Data that are passed to the Jade template are called locals. To output the value of a variable, use =
body: "The Comprehensive Book on Express.js"

Attributes

Attributes Attributes
Attributes are added by putting them into parentheses right after the tag name. They follow name=value format. In addition, multiple attributes need to be separated by a comma. For example,
Text Text
Outputting raw text is done via |—for example:
Script and Style Blocks Script and Style Blocks
Sometimes, developers want to write chunks of content for script or style tags in the HTML! This is possible with a dot. For example, we can write inline front-end JavaScript like this:
x
Install mssql driver using npm command, npm install mssql in the command prompt. This will add mssql module folder in node_modules folder in your Node.js application
Server.js
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'mypassword',
server: 'localhost',
database: 'SchoolDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Student', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.The following figure illustrates how template engine works in Node.js.
doctype html
title Jade Page
h1 This page is produced by Jade engine
p some paragraph here..
title Jade Page
h1 This page is produced by Jade engine
p some paragraph here..
Example : Server.js
var app = express();
//set view engine
app.set("view engine","jade")
app.get('/', function (req, res) {
res.render('sample');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
Data that are passed to the Jade template are called locals. To output the value of a variable, use =
p= body
title: "Express.js Guide",
body: "The Comprehensive Book on Express.js"
Attributes are added by putting them into parentheses right after the tag name. They follow name=value format. In addition, multiple attributes need to be separated by a comma. For example,
Outputting raw text is done via |—for example:
Sometimes, developers want to write chunks of content for script or style tags in the HTML! This is possible with a dot. For example, we can write inline front-end JavaScript like this:
x
Node inspector is GUI based debugger. Install Node Inspector using NPM in the global
mode by writing the following command in the terminal window (in Mac or Linux) or
npm install -g node-inspector

command prompt (in Windows).
start the node inspector on a different port using the following command.

D:\>node-inspector --web-port=5500
Node.js EventEmitter :
Node.js allows us to create and handle custom events easily by using events module.
Event module includes EventEmitter class which can be used to raise and handle custom
var emitter = require('events').EventEmitter;
em.addListener('FirstEvent', function (data) {
});
console.log('First subscriber: ' + data);
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
Express.js is a web application framework for Node.js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.js.
Express.js is based on the Node.js middleware module called connect which in turn uses http module. So, any middleware which is based on connect will also work with Express.js.
serve static resources like images, css, JavaScript or other static files using Express.js and node-static module.
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public'));
app.use(express.static(__dirname + 'public'));
//Serves resources from public folder
var server = app.listen(5000);
var server = app.listen(5000);
var express = require('express');
var app = express();
app.use(express.static('public'));
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
 app.use() method mounts the express.static middle ware for every request that starts with "/images". It will serve images from images folder for every HTTP requests that starts with "/images".
var http = require('http');
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5000);
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5000);
Node.js supports all kinds of databases no matter if it is a relational database or NoSQL database. However, NoSQL databases like MongoDb are the best fit with Node.js.
Express.js is a web application framework for Node.js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.js.
Express.js is based on the Node.js middleware module called connect which in turn uses http module. So, any middleware which is based on connect will also work with Express.js.
serve static resources like images, css, JavaScript or other static files using Express.js and node-static module.
It is easy to serve static files using built-in middleware in Express.js
called express.static. Using express.static() method, you can server
have stored your static resources.

static resources directly by specifying the folder name where you
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public'));
//Serves resources from public folder
var server = app.listen(5000);
var express = require('express');
var app = express();
app.use(express.static('public'));
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
 app.use() method mounts the express.static middle ware for every request that starts with "/images". It will serve images from images folder for every HTTP requests that starts with "/images".
you can use node-static module to serve static resources. The node-static module is
an HTTP static-file server module with built-in caching.
npm install node-static

First of all, install node-static module using NPM as below.
var http = require('http');
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5000);
Node.js supports all kinds of databases no matter if it is a relational database or NoSQL database. However, NoSQL databases like MongoDb are the best fit with Node.js.
To access the database from Node.js, you first need to install drivers for the database you want to use.
Install mssql driver using npm command, npm install mssql in the command prompt. This will add mssql module folder in node_modules folder in your Node.js application
Server.js
// config for your database
var config = {
user: 'sa',
password: 'mypassword',
server: 'localhost',
database: 'SchoolDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Student', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
console.log('Server is running..');
});
Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.The following figure illustrates how template engine works in Node.js.
Jade is a template engine for Node.js. Jade syntax is easy to learn.
It uses white space and indentation as a part of the syntax.
Jade template must be written inside .jade file.

And all .jade files must be put inside views folder in the root folder of
doctype html
title Jade Page
h1 This page is produced by Jade engine
p some paragraph here..
Node.js application
Example : Server.js
app.set("view engine","jade")
app.get('/', function (req, res) {
res.render('sample');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
Data that are passed to the Jade template are called locals. To output the value of a variable, use =
Jade

code:
h1= title
p= body
Locals:
{
title: "Express.js Guide",
body: "The Comprehensive Book on Express.js"
}
body: "The Comprehensive Book on Express.js"
Attributes are added by putting them into parentheses right after the tag name. They follow name=value format. In addition, multiple attributes need to be separated by a comma. For example,
div(id="content", class="main")
a(href="http://expressjsguide.com", title="Express.js Guide"
, target="_blank") Express.js Guide
form(action="/login")
button(type="submit, value="save")
div(class="hero-unit") Lean Node.js!
Outputting raw text is done via |—for example:
div
| Jade is a template engine.
| It can be used in Node.js and in the browser JavaScript.
Sometimes, developers want to write chunks of content for script or style tags in the HTML! This is possible with a dot. For example, we can write inline front-end JavaScript like this:
script.
console.log('Hello Jade!')
setTimeout(function(){
window.location.href='http://rpjs.co'
},200))
console.log('Good bye!')
<script>
console.log('Hello Jade!')
setTimeout(function(){
window.location.href='http://rpjs.co'
},200))
console.log('Good bye!')
</script>
To access the database from Node.js, you first need to install drivers for the database you want to use.
Install mssql driver using npm command, npm install mssql in the command prompt. This will add mssql module folder in node_modules folder in your Node.js application
Server.js
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'mypassword',
server: 'localhost',
database: 'SchoolDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Student', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.The following figure illustrates how template engine works in Node.js.
Jade is a template engine for Node.js. Jade syntax is easy to learn.
It uses white space and indentation as a part of the syntax.
Jade template must be written inside .jade file.

And all .jade files must be put inside views folder in the root folder of
doctype html
title Jade Page
h1 This page is produced by Jade engine
p some paragraph here..
Node.js application
Example : Server.js
var express = require('express');
var app = express();
//set view engine
app.set("view engine","jade")
app.get('/', function (req, res) {
res.render('sample');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
Jade is an elegant templating engine, primarily used for server-side
templating in NodeJS. In plain words, Jade gives you a powerful new
way to write markup, with a number of advantages

over plain HTML.

Body

div

h1 Practical Node.js

p The only book most people will ever need.

footer &copy; Apress
Data that are passed to the Jade template are called locals. To output the value of a variable, use =
Jade

code:
h1= title
p= body
Locals:
{
title: "Express.js Guide",
body: "The Comprehensive Book on Express.js"
}
Attributes are added by putting them into parentheses right after the tag name. They follow name=value format. In addition, multiple attributes need to be separated by a comma. For example,
div(id="content", class="main")
a(href="http://expressjsguide.com", title="Express.js Guide"
, target="_blank") Express.js Guide
form(action="/login")
button(type="submit, value="save")
div(class="hero-unit") Lean Node.js!
Outputting raw text is done via |—for example:
div
| Jade is a template engine.
| It can be used in Node.js and in the browser JavaScript.
Sometimes, developers want to write chunks of content for script or style tags in the HTML! This is possible with a dot. For example, we can write inline front-end JavaScript like this:
script.
console.log('Hello Jade!')
setTimeout(function(){
window.location.href='http://rpjs.co'
},200))
console.log('Good bye!')
<script>
console.log('Hello Jade!')
setTimeout(function(){
window.location.href='http://rpjs.co'
},200))
console.log('Good bye!')
</script>

Comments

Popular posts from this blog

Chat Bot

Entity Framework

Microsoft Enterprise Library-Data Access Application Block for for .Net Core & .Net Standard