0% found this document useful (0 votes)
10 views92 pages

Nodejs - Notes of The Webdevelopment Subject

Node.js is a server-side platform built on Chrome's V8 JavaScript Engine, designed for building fast and scalable network applications using an event-driven, non-blocking I/O model. It is open source and supports various operating systems, providing a rich library of JavaScript modules for web application development. The document also covers features, installation, creating applications, and using Express.js for building web applications with routing and middleware functionalities.

Uploaded by

mohdirfan68883
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
10 views92 pages

Nodejs - Notes of The Webdevelopment Subject

Node.js is a server-side platform built on Chrome's V8 JavaScript Engine, designed for building fast and scalable network applications using an event-driven, non-blocking I/O model. It is open source and supports various operating systems, providing a rich library of JavaScript modules for web application development. The document also covers features, installation, creating applications, and using Express.js for building web applications with routing and middleware functionalities.

Uploaded by

mohdirfan68883
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 92
Node.JS 1. INTRODUCTION Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows: Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent. Node.js = Runtime Environment + JavaScript Library Features of Node.js Following are some of the important features that make Node.js the first choice of software architects. + Asynchronous and Event Driven — All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means 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. Very Fast — Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable — Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. 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. ruc. + No Buffering — Node.js applications never buffer any data. These applications simply output the data in chunks. « License — Node.js is released under the MIT license. Who Uses Node js? Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few. « Projects, Applications, and Companies Using Node Where to Use Node.js? Following are the areas where Node.js is proving itself as a perfect technology partner. e 1/0 bound Applications e Data Streaming Applications e Data Intensive Real-time Applications (DIRT) e JSON APIs based Applications © Single Page Applications Where Not to Use Nodejs? It is not advisable to use Node.js for CPU intensive applications. 2. ENVIRONMENT SETUP * Try it Option Online * Local Environment Setup The Nodejs Runtime The source code that you would write in a source file is simply javascript. The Node.js interpreter interprets and executes your javascript code. Node.js distribution comes as a binary installable for SunOS, Linux, Mac OS X, and Windows ‘operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures. The following section explains how to install Node.js binary distribution on various OS. 3. FIRST APPLICATION Before creating an actual "Hello, World!" application using Node.js, let us see the components of a Node.js application. A Node.js application consists of the following three important components: 1, Import required modules: We use the require directive to load Node.js modules. 2. Create server: A server which will listen to client's requests similar to Apache HTTP Server. 3. Read request and return response: The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response. Creating Node.js Application Step 1 - Import Required Module We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows: var http = require("http"); Step 2 -Create Server We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return "Hello World”. http. createServer(function (request, response) { // Send the HTTP header // HTTP Status: 208 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': ‘text/plain'}); // Send the response body as "Hello World” response.end( ‘Hello World\n'); }). isten(8081); // Console will print the message console. log(‘Server running at http://127.0.0.1:8081/"); The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port on the local machine. i es Step 3 - Testing Request & Response Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below: var http = require("http"); http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(2@0, {'Content-Type': ‘text/plain'}); // Send the response body as "Hello World” response.end('Hello World\n"); }).isten(8081); // Console will print the message console. log('Server running at http: //127.0.0.1:8081/'); Now execute the main.js to start the server as follows: $ node main. js Verify the Output. Server has started. Server running at http://127.0.0.1:8081/ ee Make a Requesttto the Nodes Server Open http://127.0.0.1:8081/ in any browser and observe the following result. e0o aoe ey e © 127.0.0.1:8081 Hello World Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8081. uw VY Node Package Manager (NPM) provides two mai functionalities: * Online repositories for node.js packages/modules which are searchable on search.nodejs.org ~ . commend Tine atity to install_Node.js_ packages, do version management and dependency management of Node.js packages. NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and type the following command and see the result: —— —— $npm --version UES er We) o) Av{-sar-B Rel) 10.9.2 a Installing Modules using NPM There is a simple syntax to install any Node.js module: $ _npm install a called express: For example, following is the command to install a famous Node.js web framework module * Here local mode refers to the package installation ih node_modules directory lying in the folder where Node application is present. x JScally deployed packages are accessible Va ie method * For example, when we installed express module, it created node_modules directory in the current directory where it installed express module. Alternatively, you can us mmand to list down all the locally installed modules. Global vs Local potato Ylobally installed packages/dependencies are stored in systems > d irectory. + Such dependencies can be used in CLI (Com ine Interface) function of any node.js but cannot be imported using ire() in Node application directly. %* Now let's try installing the express module using global installation. $_npm install onees(go This will produce a similar result but the module will be installed globally. Here, the first line shows the module version and the location where it is getting installed. expres Gi 12 ) usr /1tv/node_nodutes/express You can use the following command to check all the modules installed globally $ npm 1s -g Using package,json package.json is present in the root directory of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in node_modules/express/ Check in VS Code Creating Dynamic Web Pages with Node,j What is Express JS? Express.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications. Express is the backend part of something known as the MEAN stack. 1) MongoDB 2) Express.js 3) Angular.js 4) Node.js Continue The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests. Express FrameWork help a developer to quickly build web sites with a lower the learning curve. Installation Install with NPM npm install express This command will create folder in node_modules and install the latest stable express module over there. if you want to specify the version you can pass @versionnumnber. To load express var express = require(‘express’); Object of Express There are four main object of Express: 1. Application (app) 2 .Request (req) 3 .Response (res) 4 .Router ( express.Router) Usage Express module is factory for applications var app = express(); Applications have many methods for configuring -- are also functions that can be given to standard node http and https modules Invoke app.listen() method after configuring - or give to http or https modules app.listen(3000, function(req, res){ console.log('Express JS ready for port 3000'); Wr Routing in Express 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). SYNTAX: app.METHOD(PATH, HANDLER); METHOD = GET/POST/PUT/DELETE etc Routing Example Routes are defined with URL pattern and callback Functions app.get('/login', function(req, res){ // render form di; app.post(‘/login', function(req, res) { // verify credentials and issue cookie yi Route Pattern » Patterns can be strings or regular expressions » Strings can contain param placeholders app.get('/api/user/:id', function(req, res){ var userld = req.params.id; //load user info and return JSON +); Requests Request objects expose details of HTTP requests: *req.params - route parameters in URL req.query — query string parameters req.get() - get header value req.cookies() - cookie object( requires middleware) req.body() - parsed body (requires middleware) req.is() - text content type of request body req.accepts() - content nagotiation for response req.url - URL that matched current route req.originalUrl - original url as sent by client req.protocol — http or https req.secure — true if protocol is https req.host — value in host header req.subdomains — subdomains of host req.path - path in URL rea.xhr - true if reauested with XMLHttoReauest vvv VVVVVVVVVVV Respons Many ways to respond to requests > > > > > > > > va res.set() - set response headers res.cookie() and res.clearCookie() - modify response cookies res.redirect() - issue 301 or 302 redirect to URL red.send() - write status with string/Array/Object/Buffer res.json() - stringify JavaScript value res.jsonp() - send JavaScript value to callback function res.sendfile() - stream contents of file res.download() - stream file with content-disposition: attachment res.render() — render view with pluggable view engine Middleware in Express MiddleWare performs the process before sending the request to the router. For Example, Authenticate before executing admin panel pages. You can transfer the control to the Next MiddleWare using the next() function. Types of MiddleWare: . Application level MiddleWare . Router level Middleware . Error handling Middleware . Built In MiddleWare . Third Party MiddleWare UBWNE Third Party MiddleWare: In Express JS 4, Middleware is not part of core modules. So you have to install all middleware when require List of Third Party MiddleWare. 1. Express-session : 2. request.Object: 3. Body-parser: SYNTAX: npm install body-parser Built In MiddleWare app.use(express.static('./'); Application Middleware You can have multiple application level MiddleWare. Application level middleware is refers app on MiddleWare. Express framework provides app.METHOD. Here is the list of Methods: 1. app.get 2. app.post 3. app.put Router Level MiddleWare The Route MiddleWare is work as a separate component in Express4. Here in Route MiddleWare, express binds instance of express.router object. This MiddleWare is mainly used for configuring better routing. ‘, Install Dependencies In your terminal: bash npm init -y npm install express body-parser Frontend: index.html ntml

You might also like