
Node JS Introduction
• Node.js is an open source server environment.
• Node.js is not a programming language itself. It is a platform which runs JavaScript on server side
• Node.js = Runtime Environment + JavaScript Library
• Its runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• Node.js has built-in libraries to handle web requests and responses so we don’t need a separate web server or other dependencies.
How its work ?
• Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, its used for converting javascript code to machine code faster
• I/O Non Blocking and Asynchronous : All APIs of Node.js library are asynchronous i.e. non-blocking. So a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. It is also a reason that it is very fast.
• Single threaded: Node.js follows a single threaded model with event looping. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.
• No buffering: Node.js cuts down the overall processing time while uploading audio and video files. Node.js applications never buffer any data. These applications simply output the data in chunks.
PHP VS NODE
How PHP or ASP handles a file request
• A web server sends the task to the computer's file system and its waits untill when the file system opens and reads the file then it returns the content to the client.
• When the task completed then only its ready to handle the next request.
How Node.js handles a file request
• A web server sends the task to the computer file system then immediately its ready to handle the next request. Node.js eliminates the waiting, and simply continues with the next request.
• When the file system has opened and read the file, the server returns the content to the client.
• Node.js can generate dynamic page content
• Node.js can create, open, read, write, add,modify, delete, and close files on the server and database.
• Node.js doesn’t support CPU intensive work its only work on I/O intensive.
Environmental Setup
• To install and setup an environment for Node.js, you need the following two softwares available on your computer
• Text Editor ( Visual Studio Code, Notepad++ or Notepad)
• Node.js Binary Installer.
https://nodejs.org/en/download/
• After installation open command prompt and the below command to check the version of Node JS
node -v
Sample Program
• Open your text editor and type the below code then save the file as filename.js extension.
console.log("Hello world");
• Open Your Command Prompt and enter the below comment
cd desktop
node filename.js
• Node JS Modules to be the same as JavaScript libraries.
• Node.js has a set of built-in modules which you can use in your application without any further installation.
• In Node JS , you can easily create your own modules and include in your application.
• If you want to include the in-built modules or your own modules in your application then you use the require() function with the name of the module.
Node JS Built-in Modules
• http - To make Node.js act as an HTTP server
• https - To make Node.js act as an HTTPS server.
• fs - To handle the file system
• events - To handle events
• path - To handle file paths
• url - To parse URL strings
How HTTPS Works ?
• HTTP stands for Hyper Text Transfer Protocol
• WWW is about communication between web clients and servers
• Its done by sending HTTP Requests and receiving HTTP Responses
Client Cloud Server
• A client (a browser) sends an HTTP request to the web
• An web server receives the request
• The server runs an application to process the request
• The server returns an HTTP response (output) to the browser
• The client (the browser) receives the response.
• The Node JS file system module allows you to read, write, create, update, delete or rename the files on your computer.
• In fs module, every method has synchronous and asynchronous.
• Asynchronous is better than synchronous because its never block the program during execution like synchronous.
• In Asynchronous methods take a last parameter as completion function callback.
• Inside the callback function we pass the first parameter as err for printing the error message when the file have an error.
• Import file system module using require keyword
var fs = require(‘fs’);
Read File
• fs.readFile() – Used to read the files from your computer.
• In Node JS, Read File have both synchronous and asynchronous methods.
• Synchronous
var data = fs.readFileSync(‘demo.txt');
• Asynchronous Parameters
path – File name including with path
callback - In this callback function which gets two arguments (err, data)
fs.readFile(‘demo.txt', function (err, data));
Write File
• fs.writeFile() – If file already exists then its replaces the file content. If the file does not exist, a new file will be created and specified content should be written.
path - File name including with path.
data - String to be written in file.
callback - In this callback function which gets single arguments (err) which return error in case of any error occur.
fs.writeFile(‘demo.txt', ”Hello world”, function (err));
Append File
• fs.appendFile() – Append the specified content to a file. If file doesnot exists then its create a file and append the content.
path - File name including with path.
data - String to be append in file.
callback - In this callback function which gets single arguments (err) which return error in case of any error occur.
fs.appendFile(‘demo.txt', 'Hello World', function (err));
Rename File
• fs.rename() – This method used to rename the file
Path 1 – existing file name including path
Path 2 – new file name including path
Callback – In this callback function which gets one argument (err).
fs.rename(‘demo1.txt', ‘demo2.txt', function (err))
• fs.unlink() – This method used to delete a file
Path - This is string having file name including path.
Callback - This is the callback function which gets one argument (err)
fs.unlink(‘demo.txt', function(err))
Open File
• The fs.open() method takes a "flag" as the second argument. In this method, If the file does not exist, an empty file is created.
• fs.open(path, flags[, mode], callback)
path - File name including with path.
flags - Flag specifies the behavior of the file to be opened like read / write / append.
mode - This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.
callback – In this callback function which gets two arguments (err, fd).
err – It returns error in case of any error occur.
fd − This is the file descriptor returned by fs.open().
• fs.open(“demo.txt”,w+,function(err,fd))
• Lot of Flags for Handling File System.
• Read File
1. r - read file , if it doesn’t exist its return exception
2. r+ - read and write
3. rs - read in synchronous mode
4. rs+ - read and write in synchronous mode
• Write File
1.w - write ( if file not exist then its create a file, if it exists then the file will be truncated )
2.wx - write ( if file exist its fail )
3.w+ - write and read ( if file not exist then its create a file, if it exists then the file will be truncated )
4.wx+ - write and read ( if file exist its fail )
• Append File
1.a - appending , if file not exist then its create a file
2.ax - appending , if file exist its fail
3.a+ - read and append , if file not exist then its create a file
4.ax+ - read and append , if file exist its fail
• Methods for getting file information
1.stats.isFile() - Returns true if file type is simple file.
2.stats.isDirectory() - Returns true if file type is directory.
• Path: This is string having file name including path.
• Callback: This is the callback function which gets two arguments (err, stats)
• err – Its return errors in case of any error occurs
• stats – Its an object of fs.Stats type.
fs.stat(‘demo.txt', function (err, stats))
• URL module splits up a web address into readable parts.
• Parse an address with the url.parse() method, and it will split a URL object with each part of the address as properties
http://localhost:8080/demo.html
• Host : localhost:8080
• Path name : demo.html
Note : Web servers usually respond with html documents along with images, style sheets and scripts.
• We can use Nodemailer Module to send Gmail from our system.
• Install the Nodemailer module from npm.
npm install nodemailer
• If you want to send mail from your gmail account then you must turn on the less secure apps in your google account.
https://www.google.com/settings/security/lesssecureapps
• You can compose a mail in various format such as text, html.
• Text - ‘ Hello World ‘
• Html '<h1>Welcome to VJ TECHNO WIZARD</h1><a href="www.youtube.com/vjtechnowizard">Youtube</a><br><a href="www.vjtechnowizard.blogspot.com">Blog</a><h2>Thanks for your support</h2>'
• In Node JS Formidable module used for parsing form data, especially file uploads.
• So install the formidable module from node package manager.
npm install formidable
• Type the above command in your command prompt or visual studio code terminal.
• For getting User form data we use the formidable.IncomingForm() method.
• Include the Formidable module to be able to parse the uploaded file once it reaches the server.
• The path to this directory can be found in the "files" object, passed as the third argument in the parse() method's callback function.
• form.parse(req , function (err, fields, files))
err - It returns error , incase of any error occurs
fields - Getting the user data from Form input fields (Name, Mail id, Phone number etc;)
files – When the file is uploaded and parsed, it gets placed on a temporary folder on your computer.
• MongoDB is a most popular NoSQL Database
• Node.js can be used in database applications.
• Now, We use MongoDB as a database with Node.js
• If you want to access MongoDB database by using node js then you first install MongoDB in your system.
https://www.mongodb.com
• You can download MongoDB by visit the above website
• Once you installed and running MongoDB on your system then you can access it by using Node.js
• So, You also need a MongoDB driver. You download “MongoDB" module from NPM.
npm install mongodb
RESTful API Web Service
• Web services used for exchanging data between applications or systems with the help of HTTP requests such as GET, PUT, POST and DELETE.
• Web services based on REST(Representational State Transfer) Architecture are known as RESTful web services.
• Four HTTP methods are commonly used in REST based architecture.
• GET − Used to provide a read only access to a resource.
• PUT − Used to create a new resource.
• DELETE − Used to remove a resource.
• POST − Used to update a existing resource
• A RESTful web service defines a URI (Uniform Resource Identifier), which provides various representation to represent a resources via text, JSON, XML.
• The Principles of API are stateless, uniform interface, client-server, cacheability, layered system, code on demand.
JSON
• JSON - JavaScript Object Notation.
• JSON is language independent used for storing and exchanging data between a browser and server so the data must be a text only.
• JSON text can be read by any programming language.
• JSON.stringify() convert a JavaScript object into a text/string and send JSON data to the server.
• JSON.parse() convert the text/string data to a JavaScript object when we receive the data in our browser.
• JSON uses JavaScript syntax, but the JSON format is text only.
{
"1":{"name":"Vijayakumar" , "profession":"Full Stack Developer"},
"2":{"name":"Vj Sundar", "profession":"Team Leader"}
}
Install Express JS
• Install the express framework globally to create web application using Node JS terminal.
npm install -g express
•This command install express in node_module directory and create a directory named express inside the node_module.
npm install express --save
•This command install node.js middleware for handling JSON, Raw, Text and URL encoded form data
npm install body-parser --save
•This command used to Parse Cookie header and populate req.cookies with an object keyed by the cookie names
npm install cookie-parser --save
•This command install node.js middleware for handling multipart/form-data.
npm install multer --save
Hello Guys, Now I'll give a quick intro about Node.js
Node JS Introduction
Node.js is an open source server environment.
Node.js is not a programming language itself. It is a platform which runs JavaScript on server side
Node.js = Runtime Environment + JavaScript Library
Its runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
Node.js has built-in libraries to handle web requests and responses. So, we don’t need a separate web server or other dependencies.
Why we want to learn Node.js & How its work ?
Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, its used for converting javascript code to machine code faster
I/O Non Blocking and Asynchronous : All APIs of Node.js library are asynchronous i.e. non-blocking. So a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. It is also a reason that it is very fast.
Single threaded: Node.js follows a single threaded model with event looping. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.
No buffering: Node.js cuts down the overall processing time while uploading audio and video files. Node.js applications never buffer any data. These applications simply output the data in chunks.
Difference Between PHP and Node.js
How PHP or ASP handles a file request
A web server sends the task to the computer's file system and its waits untill when the file system opens and reads the file then it returns the content to the client.
When the task completed then only its ready to handle the next request.
How Node.js handles a file request
A web server sends the task to the computer file system then immediately its ready to handle the next request. Node.js eliminates the waiting, and simply continues with the next request.
When the file system has opened and read the file, the server returns the content to the client.
Node.js can generate dynamic page content
Node.js can create, open, read, write, add,modify, delete, and close files on the server and database.
Node.js doesn’t support CPU intensive work its only work on I/O intensive.
In this course you will learn all the key concepts of Node.js. This course will helpful for you to develope a backend application using Nodejs. Following topics are covered in this course.
Introduction
How Nodejs Work
Single Thread vs Multiple Thread
PHP vs NodeJS
Git & GitHub Tutorial
Nodejs, Npm and Visual Studio Code Installation
Nodejs Modules
Nodejs Built-in Modules
How HTTP Works?
Nodejs HTTP Module
Nodejs File System Module
Web Application Architecture
How Web Server Works?
Nodejs URL Module
Send Mail Using Nodejs
Upload Files and Send Html Form
Nodejs + MySQL
MongoDB Installation and Environmetal Variable Setup
Nodejs + MongoDB
RESTful API
JSON
Express JS Installation
CRUD Application