Language: English

Introduction of Node.js

What is Node.js?

It is a very powerful JavaScript-based framework which is built on Google Chrome’s JavaScript V8 Engine. It is basically used to develop I/O intensive web applications like single-page applications, video streaming sites and other web applications. There are following points to remember about Node.js:

  • Node.js is an open source server framework
  • Node.js is free
  • Node.js runs on various platforms (Windows, Linux, UNIX, Mac OS X, etc.)
  • Node.js uses JavaScript on the server

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
  3. Advertisement servers

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 not to use Node.js

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.

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.

 

How to download Node.js

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

My first “Hello World” application

Before creating an 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 −

  • Import required modules− use the require directive to load Node.js modules.
  • Create server– A client requests listen by server which is similar to Apache HTTP Server.
  • Read request and return response− 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.

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 listenmethod 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: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(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 xxxx port on the local machine.

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(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:xxxx/');

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:xxxx/

Convert JSON to DataTable

JSON in the following format –

[
    {"id":"10","name":"User","add":false,"edit":true,"authorize":true,"view":true},
    {"id":"11","name":"Group","add":true,"edit":false,"authorize":false,"view":true},
    {"id":"12","name":"Permission","add":true,"edit":true,"authorize":true,"view":true}
]

Need to convert that into a C# DataTable object as follows :-

---------------------------------------------------------------------
ID    |  Name     |  Add    |   Edit  | View   | Authorize
---------------------------------------------------------------------
10    | User      | true    |  true   | true   |  true
11    | Group     | true    |  true   | true   |  true
12    | Permission| true    |  true   | true   |  true

Deserialize your jsonstring to some class –

List UserList = JsonConvert.DeserializeObject>(jsonString);

Write following extension method to your project –

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
    TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
    PropertyDescriptor prop = props[i];
    table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
    for (int i = 0; i < values.Length; i++)
    {
        values[i] = props[i].GetValue(item);
    }
    table.Rows.Add(values);
    }
    return table;        
}

Call extension method like

UserList.ToDataTable<User>();




Categories
Links: