Friday, November 6, 2015

Nodejs n Java - Using Java code in NodeJS

Being a seasoned java developer, switching to NodeJS and dealing with the way Nodejs works is quite challenging. Plus, what about the work done in the Java, isn't we have to redo all that thing in Nodejs... well, what if i say No...

NodeJS is too open, and with the NAN library (native abstractions for Node) it does provide a way to use Java libraries and your custom code in NodeJS. Since node  is being developed in C++ there are ways to invoke C++ code in NodeJS, however this kept changing between Node V0.10.x n V0.12.7. I really found it a bit on the higher end of learning curve although its great and fun experience to work with it. However with the complexity, i also decided to try another road. Since it is my bread and butter for quite long time, it seems to be good chance to go back in the old territory and see, how things can be bridged.

Enough talk lets start coding...
I have uploaded all the Java + NodeJS code on my Github repo

Basically, we have to use two NPM module "java" which acts as a wrapper across the Java API's and 'node-java-maven' through which we can use any library present under MVN repo... well everything is available under MVN,, isnt???/

Steps to run the example
1. Clone the repo and do an "npm install" .
2. execute "node index.js" . This file will simply replicate the functionality of and simply invoke every function present in it. (without argument, with integer argument, with String argument, calling instance n static methods, getting a returned value from the Java program.
3. execute "node maven.js" -> This will replicate the functionality of (which will be using Apache commons lang ver 3.0)... Open package.json and see the "java" keyword . yes we can specify any java library via this and can load this in our nodejs program before executing any java code.

I have purposely created a lib directory which will contains the custom code that we have written via using Apache Commons Lang and the whole maven project is being included undeer "NodeSample" folder in the Git Repo.

Every Java function, can be called either in an SYNCHRONOUS or Asynchronous manner. Both of the programs have an example of this.

Here are some of the detailed links that will be helpful.    -> Github repo of actual 'java' module -> github Repo of actual 'node-java-maven' module.

I hope this will prove helpful for daily Nodejs programmer or the Java guys who are making a shift to NodejS (like me... ummmm.). Let me know if there is a problem.

1 comment:

  1. Nodejs is an open source and cross platform environment for developing the server side web application. The main advantage of using nodejs is because of its fastness, single threaded and highly scalable.
    Node JS training in chennai | Node JS training institute in chennai