Skip to main content

NODEJS TUTORIAL



Introduction:-  
Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Typically, JavaScript is used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a webpage's HTML and run client-side by a JavaScript engine in the user's web browser. Node.js lets developers use JavaScript to write Command Line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Consequently, Node.js represents a "JavaScript everywhere" paradigm, unifying web application development around a single programming language, rather than different languages for server side and client side scripts.
Though .js is the conventional filename extension for JavaScript code, the name "Node.js" does not refer to a particular file in this context and is merely the name of the product. Node.js has an event-driven architecture capable of asynchronous I/O. These design choices aim to optimize throughput and scalability in web applications with many input/output operations, as well as for real-time Webapplications (e.g., real-time communication programs and browser games).
The Node.js distributed development project, governed by the Node.js Foundation, is facilitated by the Linux Foundation's Collaborative Projects program.
Corporate users of Node.js software include GoDaddy, Groupon, IBM, LinkedIn, Microsoft, Netflix,PayPal, Rakuten, SAP, Voxer, Walmart, and Yahoo!.
Why use Node.js?
We will have a look into the real worth of Node.js in the coming chapters, but what is it that makes this framework so famous. Over the years, most of the applications were based on a stateless request-response framework. In these sort of applications, it is up to the developer to ensure the right code was put in place to ensure the state of web session was maintained while the user was working with the system.
But with Node.js web applications, you can now work in real-time and have a 2-way communication. The state is maintained, and the either the client or server can start the communication.

Features of Node.js

Let's look at some of the key features of Node.js
1.    Asynchronous event driven IO helps concurrent request handling – This is probably the biggest selling points of Node.js. This feature basically means that if a request is received by Node for some Input/Output operation, it will execute the operation in the background and continue with processing other requests.
This is quite different from other programming languages. A simple example of this is given in the code below
var fs = require('fs');
          fs.readFile("Sample.txt",function(error,data)
          {
                console.log("Reading Data completed");
     });
·        The above code snippet looks at reading a file called Sample.txt. In other programming languages, the next line of processing would only happen once the entire file is read.
·        But in the case of Node.js the important fraction of code to notice is the declaration of the function ('function(error,data)'). This is known as a callback function.
·        So what happens here is that the file reading operation will start in the background. And other processing can happen simultaneously while the file is being read. Once the file read operation is completed, this anonymous function will be called and the text "Reading Data completed" will be written to the console log.
2.    Node uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node also become faster.
3.    Handling of concurrent requests – Another key functionality of Node is the ability to handle concurrent connections with a very minimal overhead on a single process.
4.    The Node.js library used JavaScript – This is another important aspect of development in Node.js. A major part of the development community are already well versed in javascript, and hence, development in Node.js becomes easier for a developer who knows javascript.
5.    There are an Active and vibrant community for the Node.js framework. Because of the active community, there are always keys updates made available to the framework. This helps to keep the framework always up-to-date with the latest trends in web development.




Who uses Node.js
Node.js is used by a variety of large companies. Below is a list of a few of them.
  • Paypal – A lot of sites within Paypal have also started the transition onto Node.js.
  • LinkedIn - LinkedIn is using Node.js to power their Mobile Servers, which powers the iPhone, Android, and Mobile Web products.
  • Mozilla has implemented Node.js to support browser APIs which has half a billion installs.
  • Ebay hosts their HTTP API service in Node.js

When to Use Node.js
Node.js is best for usage in streaming or event-based real-time applications like
1.    Chat applications
2.    Game servers – Fast and high-performance servers that need to processes thousands of requests at a time, then this is an ideal framework.
3.    Good for collaborative environment – This is good for environments which manage document. In document management environment you will have multiple people who post their documents and do constant changes by checking out and checking in documents. So Node.js is good for these environments because the event loop in Node.js can be triggered whenever documents are changed in a document managed environment.
4.    Advertisement servers – Again here you could have thousands of request to pull advertisements from the central server and Node.js can be an ideal framework to handle this.
5.    Streaming servers – Another ideal scenario to use Node is for multimedia streaming servers wherein clients have request's to pull different multimedia contents from this server.
Node.js is good when you need high levels of concurrency but less amount of dedicated CPU time.
Best of all, since Node.js is built on javascript, it's best suited when you build client-side applications which are based on the same javascript framework.

When to not use Node.js

Node.js can be used for a lot of applications with various purpose, the only scenario where it should not be used is if there are long processing times which is required by the application.
Node is structured to be single threaded. If any application is required to carry out some long running calculations in the background. So if the server is doing some calculation, it won't be able to process any other requests. As discussed above, Node.js is best when processing needs less dedicated CPU time.

Download Node.js

The official Node.js website has installation instructions for Node.js: https://nodejs.org

Getting Started

Once you have downloaded and installed Node.js on your computer, lets try to display "Hello World" in a web browser.
Create a Node.js file named "myfirst.js", and add the following code:
myfirst.js
var http = require('http');

http.createServer(
function (req, res) {
    res.writeHead(
200, {'Content-Type''text/html'});
    res.end(
'Hello World!');
}).listen(
8080);
Save the file on your computer: C:\Users\Your Name\myfirst.js
The code tells the computer to write "Hello World!" if anyone (e.g. a web browser) tries to access your computer on port 8080.
For now, you do not have to understand the code. It will be explained later.

Command Line Interface

Node.js files must be initiated in the "Command Line Interface" program of your computer.
How to open the command line interface on your computer depends on the operating system. For Windows users, press the start button and look for "Command Prompt", or simply write "cmd" in the search field.
Navigate to the folder that contains the file "myfirst.js", the command line interface window should look something like this:
C:\Users\Your Name>_

Initiate the Node.js File

The file you have just created must be initiated by Node.js before any action can take place.
Start your command line interface, write node myfirst.js and hit enter:
Initiate "myfirst.js":
C:\Users\Your Name>node myfirst.js
Now, your computer works as a server!
If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in return!
Start your internet browser, and type in the address: http://localhost:8080


Node.js Modules

What is a Module in Node.js?

Consider modules to be the same as JavaScript libraries.
A set of functions you want to include in your application.

Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.
Look at our Built-in Modules Reference for a complete list of modules.

Include Modules

To include a module, use the require() function with the name of the module:
var http = require('http');
Now your application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
    res.writeHead(
200, {'Content-Type''text/html'});
    res.end(
'Hello World!');
}).listen(
8080);

Create Your Own Modules

You can create your own modules, and easily include them in your applications.
The following example creates a module that returns a date and time object:

Example

Create a module that returns the current date and time:
exports.myDateTime = function () {
    
return Date();
};
Use the exports keyword to make properties and methods available outside the module file.
Save the code above in a file called "myfirstmodule.js"

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

Example

Use the module "myfirstmodule" in a Node.js file:
var http = require('http');
var dt = require('./myfirstmodule');

http.createServer(
function (req, res) {
    res.writeHead(
200, {'Content-Type''text/html'});
   
 res.write("The date and time are currently: " + dt.myDateTime());
    res.end();
}).listen(
8080);
Notice that we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
C:\Users\Your Name>node demo_module.js
If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080



Comments

  1. Thanks for this great post, i find it very interesting and very well thought out and put together. I look forward to reading your work in the future.
    nodejs software developers

    ReplyDelete
    Replies
    1. Hi Jonsina, Thanks for your valuable feedback. I'll try to post new ASAP. Please conider sharing this post.

      Delete
  2. 888스포츠 코리아 도메인 (4포츠 포츠). Sort & Filters · 888포츠 포츠 코리아 도메인 포츠코리아 도메인 포츠코리아 도메인 포츠코리아 도메인 포� 카지노 카지노 12bet 12bet 647Can a Las Vegas gambling machine near me?

    ReplyDelete
  3. Great website you have got here.quackity merch Keep up the good work and thanks for sharing your blog site it really help a lot.

    ReplyDelete
  4. Poker Rooms Near Me - Missouri Casinos | JTHub
    Find 성남 출장샵 the best Poker Room 밀양 출장샵 Near Me in 2021 There 경기도 출장마사지 are also poker room options near me near me near you from 계룡 출장샵 our nearby casinos. 보령 출장안마

    ReplyDelete
  5. Hi, Thanks for your valuable feedback. I'll try to post new ASAP. Please conider sharing this post.

    ReplyDelete
  6. If you do, goes to|she's going to} cause a penalty to fall on you, reducing your well being to 1. You’ve heard the time period “complication” used when referring to high-end watches, but lighters? Dupont has borrowed this vocabulary from the rarified world of horology and utilized it to its latest project, the Casino Pocket Complication Lighter. Dupont’s a hundred and fiftieth anniversary in opulent fashion, and contains 토토사이트 a working roulette wheel within the unit. Mega Sic Bo is the first sport in Pragmatic Play's live offering that includes random "Mega Multipliers", thus making certain huge win probabilities and an engaging gameplay.

    ReplyDelete

Post a Comment

Popular posts from this blog

Getting Started with Deno.js | How to Install Deno.js | Deno.js

Getting Started with Deno.js Introduction to Deno.js It’s not been so long since. The creator of Node.js   has been working on a new JavaScript runtime called Deno that heals some of the problems identified in Node.Js . Deno  is a runtime for JavaScript and TypeScript this is based on chrome V8 Javascript engine and the rust programming language. It was created by Ryan Dhal , Orignal creator of  Node.js  and is focused on productivity. Deno  explicitly takes on the role of both runtime and a package manager with a single executable, rather than a separate package-management program.  Features An improved Security Model Decentralized Package Management Standard Library Built in Tooling Installation: Deno  works on macOS, Linux and Windows.  Deno  is a single binary Executable. It has no external dependency. Download and Install: deno_install  provides convenience scripts to download and install the binary. Using Shell (macOS,

Python

Python is a powerful and versatile programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and more. In this tutorial, we'll cover some of the basics of the language to help you get started with writing your own Python programs. Getting started with Python To start using Python, you'll need to install it on your computer. You can download the latest version of Python from the official website ( https://www.python.org/downloads/ ). Once you have Python installed, you can start writing and running Python code. You can use a simple text editor (like Notepad or TextEdit) to write your code, or you can use an integrated development environment (IDE) like PyCharm or IDLE. To run a Python script, you can simply open a command prompt or terminal window and navigate to the directory where your script is saved. Then, type "python" followed by the n