1.0 Node JS - senthilpazhani/ReactJS GitHub Wiki

Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.

A common task for a web server can be to open a file on the server and return the content to the client.

Here is how PHP or ASP handles a file request:

  • Sends the task to the computer's file system.
  • Waits while the file system opens and reads the file.
  • Returns the content to the client.
  • Ready to handle the next request.

Here is how Node.js handles a file request:

  • Sends the task to the computer's file system.
  • Ready to handle the next request.
  • When the file system has opened and read the file, the server returns the content to the client.

Node.js eliminates the waiting, and simply continues with the next request.

Example

 var http = require('http');
 
 http.createServer(function (req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World!');
 }).listen(8080);

Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.

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/plain'});
     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

Ref https://www.youtube.com/watch?v=YfD5HO-iyIk&list=PL_9uM5be2amruC2K3JhZKRSnjXanhvr3u&index=10