Tag Archives: Node Js

IS NODE.JS REPLACING JAVA MIDDLEWARE SERVICES?

Is Node.js replacing Java middleware services?

In the history of computing, first in 1995, Java has come into existence, then close on its heels came JavaScript. The names made them seem like adjoined twins which are newly detached, but they are not different. One of them are compiled and statically typed and the other interpreted and dynamically typed. That is only at the beginning of the technical differences between these two fiercely distinct languages after that, it has been shifted on to a collision course of sorts, thanks to Node.js.

The Node.js was spawned, turning the developer’s heads with its speed. Not only it is faster than the JavaScript on the server but it was often faster than Java and other options. It’s small, quick, and endless requests for data have made Node.js more common, as web pages have grown more dynamic.

Node’s event-driven concurrency

Node is scalable, event-driven I/O environment built on top of Google’s V8 JavaScript engine. Google V8 complies JavaScript into the native machine code prior to execution, resulting in extremely fast runtime performance, something is not typically associated with JavaScript. As such, Node.js enables a developer to rapidly build the network apps which are lightning fast and highly concurrent.

Event-driven I/O might sound foreign to a Java developer, but it is not all that new. Rather than the multithreaded programming model which a developer was using in Java platform. Node’s approach to concurrency is single threaded, with the additional kick of an event loop. The Node construct enables non-blocking or asynchronous I/O.

Concurrency really works in Node.js. If suppose you wanted to run the previous scenario on the Java platform, then you would have the choice of complex and time-consuming approaches like from traditional threads to newer libraries in Java NIO. The Java concurrency is powerful and it is difficult to understand. By comparison, Node’s concurrency model is extremely simple, and that makes it accessible to a wider number of developers.

Node.js is ready for enterprise deployment

Node.js appeals to a wide range of the tech community because, it has a reputation for well scaling, being secure, and easy to learn. It’s not hard for a developer to pick-up Node.js and can quickly become productive with it. There are many well-known organizations like PayPal, LinkedIn, Netflix, and The New York Times using Node.js in production.

If you are building your next generation applications especially like API’s for mobile and web integration in IOT or if you are creating something very new that depends on those underlying services, then Node.js is a runtime system that could work for you very well.

Frameworks: We all know Java is all about open source frameworks. That is the main reason for its popularity. Whereas Node is much newer, many people have already done quite a bit of heavy lifting and have shared their code with the world. Below are some of the Node.js frameworks which are equivalently good for mapping the popular Java frameworks.

Web MVC: In the land of Java many people are familiar with Web MVC frameworks like Spring MVC, Struts, Wicket, and JSF. Nevertheless, a good comparable Node.js web framework is Express.js, Meteor.js, Sails.js, Derby, and SocketStream. Many of the developers go with Sails.js due to its permissive license, robust community, and flexibility. In other sense, it is even more than a web framework because it also provides most of the “web server” functionality where most of the Java developers use Tomcat, Jetty etc.

  • Rapid and agile development: With Sails.js it is very easy and quick to get stuff and can used prototype. You can iterate more quickly. It is easy to view and test changes needed which is not possible in the case of Java.
  • Package management tools: Maven is the most popular build management tool for Java. It is very flexible and powerful with a wide variety of plug-ins. NPM is the mainstream package manager for Node.js. It is light, faster and useful.

The Below is the sample code for Node.JS and Java:

Code for Node.JS and Java
Final Word

There are many number of factors to be considered when you are choosing a platform for your enterprise applications or for customers. When any presence has debated the adoption of Java or Node.js for your enterprise development platform, the decision is not that obvious or cannot be made overnight. In the end, the scalability, speed, and enterprise readiness are to be considered while choosing a platform.

WHAT IS STDOUT FLUSH IN NODEJS?

What is Stdout flush in NodeJS?

For example

sys.stdout.write(“hello I am Writing something”);
sys.stdout.flush();

Stdout flush is used for checking writable stream is “write” successful or not.

“sys.stdout.flush()” gives result true if flush was successful and false if kernel buffer is full and it can’t write yet.
 
 
 
 
 

NODE.JS FRAMEWORK COMPARISON

Node.js Framework Comparison

Express.js, Koa.js and Hapi.js are the most popular Node.js application frameworks of today and all of them have obvious similarities. Node.js frameworks enable web developers to create a server with few lines of code and creating REST API has become very simple.

Express.js

Express.js is undoubtedly the most popular Node.js application framework in contemporary web development world. Popular frameworks like Sails.js are built based on Express.js and it was described as a “fast and small server side Javascript web development framework built on node.js and V8 Javascript engine” in a web development journal. The current version of Express.js is 4.x

Express.js gained prominence as a web application framework for building single page and multi-page web apps. The finest attraction of Express.js is that many of its features are available as plug-ins and it is the backend component of MEAN stack(MongoDB ExpressJS AngularJS NodeJS). Douglas Christopher and Wilson are the developers of Express.js and it is a cross platform operating system.

Express.js can be downloaded using NPM and the command ‘npm install-g express’ in the node CLI for installing Express.JS. The quickest and easiest way to create express application architecture is to install express generator. Setting for Express applications can be obtained using the app.set and app.get methods. Application level, router level, third party and cookie middleware are available in Express.js web framework. Biggest contribution of Express.js is that it gave backend functionality that allows developers to build software with script on the server side. They can develop server side applications with Node.js and publish those ap plications as websites using Express.js.

var express = require(‘express’);
var app = express();

app.get(‘/’, function (req, res) {
res.send(‘Hello World!’);
});

var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;

console.log(‘Example app listening at http://%s:%s’, host, port);
});

” The app starts a server and listens on port 3000 for connection. It will respond with “Hello World!” for requests to the root URL (/) or route. ”

KoA.JS

Koa.js is termed as the next generation web application framework for the one and only Node.js. Objective of Koa development team was to build a smaller, expressive and robust foundation for web applications. Koa application is an object containing a wide array of middleware generator functions and they are composed in a stack like manner. Koa is almost similar to other middleware systems like Ruby’s Rack, Connect and so on. Content negotiation, cache freshness and proxy support are the spectacular features provided by Koa.js. It allows performing actions downstream, filter and then manipulating the response upstream. Methods common to all HTTP servers can be integrated directly into Koa’s small 550 SLOC database. This includes numerous functionalities like content negotiation, nominalization of node inconsistencies and redirection. Koa.js is not bundled with any middleware and it is supported in all versions of iojs without any flags. Web developers all over the world were super excited after the initial release of Koa.js and the curious fact is that Koa.js was developed by the same team who developed Express.js.

Koa is known for heavily leveraging Javascript generators provided by Harmony and Javascript generators refer to an experimental technology.

A simple hello world program in Koa.js is illustrated below.

1: var koi = require (‘koi’);
2: var app = koi ();
3:
4: app. use (function *() {
5: this. Body = ‘Hello World';
6 :});
7:
8: app. listen (3000);

We should be running node 0.11.9 or higher along with harmony flag for Javascript generator support. Koa is an innovative and pragmatic Node.js framework which can be used for building complex web applications.

HAPI.JS

Being known as a rich framework for building web applications, Hapi.js enables developers to focus on writing reusable application logic. Hapi is currently used by global corporate giants including PayPal, Walmart, Yahoo as well as Mozilla. As a web application framework, Hapi.js enables granular control over incoming requests. Hapi plug-ins can be broken into small applications with separate business logic very easily and servers should provide only configuration. In tech world, Hapi is being recognized as a battle tested framework for Node.js made by Walmart.

Hapi features huge amount of well maintained official plug-ins including OAuth. Configuration over convention approach of Hapi.js has become a hot topic of discussion among web development experts who are more inclined to convention-overconfiguration approach. Official version is that configuration based approach made the implementation of requirement theme very easy. Hapi.js will be an ideal tool for web developers who are keen on high availability, easy testing as well as easy theming.

var Hapi = require(‘hapi’);

var server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
method: ‘GET’,
path: ‘/’,
handler: function (request, reply) {
reply(‘Hello, world!’);
}
});
server.start(function () {
console.log(‘Server running at:’, server.info.uri);
});

Save the above as server.js and start the server with the command node server.js. Now, if you visit http://localhost:3000 in your browser, you’ll see the text Hello, world!.

NODE.JS IS A SINGLE THREAD APPLICATION. DOES IT SUPPORT MULTI-PROCESS OR PLATFORMS AND UTILIZE ALL THE PROCESSOR RESOURCES?

Node.js is a single thread application. Does it support multi-process or platforms and utilize all the processor resources?


Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources.


It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port

BEST NODE.JS PERFORMANCE TIPS YOU CAN ADOPT

Best Node.js Performance Tips You Can Adopt

All of us know about the rapid adoption of JavaScript in the previous decade and major reason behind the popularity of JavaScript is the influence of Node.js. Node.js is the software platform used for building fast, robust and scalable network applications. It is mainly based on Google’s V8 Javascript search engine or the Chrome browser runtime. Node.js features an event­driven architecture and an I/O API that optimizes application scalability. One of the most important feature of Node.js is that it contains built­in library that acts as a web server and there is no need for web server such as IIS or Apache Web Server.

It is perceived that Javascript is the most used language on GitHub. Ryan Dahl, the creator of Node.js says , “ after over twenty years of stateless­web based on the stateless request-response paradigm, we finally have web applications with real time two way connections”. Need for adapting to the new technology of Node.js is actively discussed in global tech community including these prominent performance tips.

Going Asynchronous
Node.js is single threaded and there are lots of synchronous components that can lock up the entire application. It is practical to use an external library that has a blocking call and use of asynchronous API is the best possible solution. While choosing third party modules, it is to be ensured that external library does not revert to synchronous calls.

Keeping Code Small
Keeping code small and light is one of the most talked about node.js performance tips we can adopt. In the contemporary age of critical mobile application performance, it is important to keep Node.js code as compact as possible. Node.js is made compact for reducing latency as well as speeding things up.

Developers of node.js face the following questions during development stage

  • “Do we really need this module”?
  • “Why are we using this framework”?
  • “Is it worth the overhead”?

“Is there another way to optimize application performance by concatenating multiple JS files into one?”­ This statement can be explained with the help of an example. If a web app has five Javascript files, the browser will make five separate HTTP requests to fetch them and the best approach would definitely be to concatenate those five files into a single one.

DO NOT use Node.js for static assets:
Don’t use Nodejs to serve static assets like client JS, CSS, fonts or images. This is not good because Node doesn’t do this efficiently. Say we ask for a reasonably large image file and we’re serving it from a Express mount-point, this works when we’re developing it locally, because it’s just us using it. No load really. Use NGINX or CDN to deliver such static assets to reduce the load on your application server.

Don’t Store Too Much in Sessions
By default in a typical Express web app, the session data is stored in memory. Storing too much data in the session, it adds significant load to the server. Instead storing their id in the session will reduce the load on an app server rather than storing the entire object. So, either you can switch to different storages like MongoDB or Redis to store session data or go session­free with EXPRESS JS.

Here is an example of initializing the session.
app.use(express.session({ secret: “mysterious triangle” }));

Run in Parallel
Generally if we want to run multiple functions at a time, we need to wait for the previous function to execute. So to reduce latency we can go for parallel operations to run. To execute these calls in parallel, we can use Step.JS (A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless). This accepts any number of functions as arguments and runs as the callback to the next step.

Use Client Side Rendering When Possible
DO NOT render (or send) templates from Node JS side. Do it on client side using templating engines like Handlebar. Infact better do it using CDN so it can be cached. For dynamic content (like data), deliver it via JSON. So after the initial page load, the only data sent to the client is the dynamic JSON, which is maximally efficient. This approach dramatically reduces the CPU, IO, and load on Node.js.

Major companies using NODEJS and Why?
Global business giants like PayPal, Yahoo, EBay, Netflix, The Mail Online, and Walmart are betting big on Node.js. Tech giants are passionate of embracing power of Node.js for embedded devices and robotics. Node.js dominates the real time web application arena by using push technology that gives them a distinctive edge over server side web applications.

Chat applications are classic examples of lightweight, real time and data intensive applications of Node.js. It has been debated that two way communication and communication has been there since many years in the form of Java applets or Flash.

The promising technology of Node.js plays a pivotal role in the technology realm of any large business organization. What would be the possible reason? It is only because Node.js allows web developers to build one code base using one language. Performance, scalability, and short web development cycles help Node.js to find a place in the big league of technology innovations in 21st century.

“Node.js powers our web applications and has allowed our teams to move much faster in bringing their designs to life”­ PayPal

WHICH TOOLS COULD BE USED TO DEBUG NODE.JS APPLICATIONS?

Which tools could be used to debug Node.js applications?

Many times when a complex situation arises. A good debugging tool will make our lives easy. Here some of the tools that you may consider to “npm install”

  1. node­inspector
  2. Joyent
  3. Node Webkit Agent
  4. NodeJS Plugin for WebStrom
  5. Cloud9 IDE (has built in debugger for Node)

 
 

HOW TO PASS COMMAND LINE ARGUMENTS TO NODE.JS?

How to pass command line arguments to Node.js?

Three ways to pass the command line arguments to node.js

  • Using process.argv – process.argv is an array containing the command line arguments. The first element will be ‘node’, the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

// print process.argv
process.argv.forEach(function (val, index,
array) {
console.log(index + ‘: ‘ + val);
});
This will Genearate,
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four

  • Using yargs module – It is a light-weight option parsing with an argv hash.
  • Using minimist module – It is a module which parse argument options.