From Java to Node.js

I’ve been developing for quite a while and in quite a few languages.  Somehow though, I’ve always seemed to fall back to Java when doing my own stuff – maybe partly from habit, partly because it has in my opinion the best open source selection out there, and party because I liked its mix of features and performance.

Specifically though, in the web arena things have been moving fast and furious with new languages, approaches, and methods like RoR, Play!, and Lift (and many others!).  While I “get it” regarding the benefits of these frameworks, I never felt the need to give them more than an initial deep dive to see how they work.  I nod a few times at their similarities and move on back to plain REST-ful services in Java with Spring, maybe an ORM (i try to avoid them these days), and a JS-rich front-end.

Recently, two factors made me deep dive into Node.js.  First is my growing appreciation with the progress of the JavaScript front-end.  What used to be little JavaScript snippets to validate a form “onSubmit” have evolved to a complete ecosystem of technologies, frameworks, and stacks.  My personal favorite these days is Backbone.js and try to use it whenever I can.

Second was the first hand feedback I got from a friend at Voxer about their success in using and deploying Node.js at real scale (they have a pretty big Node.js deployment).

So I jumped in.  In the short time I’ve been using it for some (real) projects, I can say that it’s my new favorite language of choice.

First of all, the event-driven (and non-blocking) model is a perfect fit for server side development.  While this has existed in the other languages and forms (Java Servlet 3.0, Event Machine, Twisted to name a few), I connected with the easy of use and natural maturity of it in JavaScript.  We’re all used to using callbacks anyway from your typical run-of-the-mill AJAX work right?

Second is the community and how large its gotten in the short time Node has been around.  There are lots of useful open source libraries to use to solve your problems and the quality level is high.

Third is that it was just so easy to pick up.  I have to admit that my core JavaScript was decent before I started using Node, but in terms of the Node core library and feature set itself, it’s pretty lean and mean and provides a good starting point to build what you need in case you can’t find someone who already did (which you most likely can).

So having said all that, I wanted to share what resources helped me get up to speed in Node.js coming from a Java background.

Getting to know JavaScript

There are lots of good resources out there on Node.js and i’ve listed them below.  For me, the most critical piece was getting my JavaScript knowledge to the next level.  Because you’ll be spending all your time writing your server code in JavaScript, it pays huge dividends to understand how to take full advantage of it.

As a Java developer you’re probably trained to think in OO designs.  With me, this was the part that I focused the most on.  Fortunately (or unforunately), JavaScript is not a classic OO language.  It can be if you shoehorn it, but i think that defeats the purpose.

Here is my short list of JavaScript resources:

  1. JavaScript: The Good Parts – Definitely a requirement.  Chapters 4 and 5 (functions, objects, and inheritance) are probably the most important part to understand well for those with an OO background.
  2. Learning Javascript with Object Graphs (part 2, and part 3) – howtonode.org has lots of good Node material, but this 3 part post is a good resource to top off your knowledge from the book.
  3. Simple “Class” Instantiation – Another good post I read recently.  Worth digesting.

Learning Node.js

With a good JavaScript background, starting to use Node.js is pretty straightforward.  The main part to understand is the asynchronous nature of the I/O and the need to produce and consume events to get stuff done.  Here is a list of resources I used to get up to speed:

  1. DailyJS’s Node Tutorial – A multipart tutorial for Node on DailyJS’s blog.  It’s a great resource and worth going through all the posts.
  2. Mixu’s Node Book – Not complete, but still worth it.  I look forward to reading the future chapters.
  3. Node Beginner Book – A good starter read.
  4. How To Node – A blog dedicated to Node.js.  Bookmark it.

I felt that going through these was more than enough to give me the push I needed get started.  Hopefully it does for you too (thanks to the authors for taking the time to share their knowledge!).

Frameworks?

Java is all about open source frameworks.  That’s part of why it’s so popular.  While Node.js is much newer, lots of people have already done quite a bit of heavy-lifting and have shared their code with the world.  Below is what I think is a good mapping of popular Java frameworks to their Node.js equivalents (from what I know so far).

Web MVC

In Java land, most people are familiar with Web MVC frameworks like Spring MVC, Struts, Wicket, and JSF.  More recently though, the trend towards client-side JS MVC frameworks like Ember.js (SproutCore) and Backbone.js reduces the required feature-set of some of these frameworks.

Nonetheless, a good comparable Node.js web framework is Express.   In a sense, it’s even more than a web framework because it also provides most of the “web server” functionality most Java developers are used to through Tomcat, Jetty, etc (more specifically, Express builds on top of Connect)  It’s well thought out and provides the feature set needed to get things done.

Application Lifecycle Framework (DI Framework)

Spring is a popular framework in Java to provide a great deal of glue and abstraction functionality.  It allows easy dependency injection, testing, object lifecycle management, transaction management, etc.  It’s usually one of the first things I slap into a new project in Java.

In Node.js… I haven’t really missed it.  JavaScript allows much more flexible ways of decoupling dependencies and I personally haven’t felt the need to find a replacement for Spring.  Maybe that’s a good thing?

Object-Relational Mapping (ORMs)

I have mixed feelings regarding ORMs in general, but it does make your life easier sometimes.  There is no shortage of ORM librares for Node.js.  Take your pick.

Package Management Tools

Maven is probably most popular build management tool for Java.  While it is very flexible and powerful with a wide variety of plug-ins, it can get very cumbersome.  Npm is the mainstream package manager for Node.js.  It’s light, fast, and useful.

Testing Framework

Java has lots of these for sure, jUnit and company as standard.  There are also mock libraries, stub libraries, db test libraries, etc.  Node.js has quite a few as well.  Pick your poison.  I see that nodeunit is popular and is similar to jUnit.  I’m personally testing Mocha.  Testing tools are a more personal and subjective choice, but the good thing is that there definitely are good choices out there.

Logging

Java developers have quite a list of choices when choosing a logger library.  Commons logging, log4j, logback, and slf4j (wrapper) are some of the more popular ones.  Node.js also has a few.  I’m currently using winston and have no complaints so far.  It has the logging levels, multiple transports (appenders to log4j people), and does it all asynchronously as well.

Hopefully this will help someone save some time when peeking into the world of Node.  Good luck!

Advertisement

50 Responses to From Java to Node.js

  1. Biomechanica says:

    I’m intersted: How is the performanced compared to a Java backend?

  2. mscdex says:

    A couple additional “learning node.js” links are: http://nodetuts.com/ and http://nodeguide.com/

  3. Great summary! Thanks!

  4. Thanks for the article!

    @Biomechanica
    Node.js is way faster than Java for server related stuff. (sockets for example)

    • Benjamin Erb says:

      I also come from a Java background and appreciate node.js. However, I think that this is an inappropriate generalization. Using efficient java.nio techniques still yields better results than node.js most of the times (with a much heavier footprint though).

      I recently tested several Java-based HTTP servers against node.js using a simple “hello world” response. Surpringsinly, most of the Java servers outperformed node.js, even when unsing multiple node instances (#cores). Again, the JVM footprint was much larger, and real web applications have different characteristics than simple “hello world” responses. But I’d be careful with such general statements.

      • matan says:

        Good point Benjamin.

        From my experience, performance is a tough question to answer because you really have to think of the system as a whole. The weakest link (slowest piece) usually dictates the overall system perceived performance. Having a slow DB isn’t going to make your choice of Java or Node.js matter that much…

        So assuming that everything else is equal (like architecture, data structure choices, database driver quality, database design and queries, etc) it might be that Java is faster.. but it might be a moot point.

        Writing asynchronous code in Node.js is much more convenient than Java and helps in doing more at the same time so that you aren’t waiting for all those database queries to run one after the other, for example. Check out the Node.js async module for some cool patterns to use (https://github.com/caolan/async).

        In all, I wouldn’t make the choice to move to Node.js because it has better performance or not, but the overall holistic view.

      • Xavier Mendez says:

        Yes, I can always make java.nio programs that (lower level, higher footprint and code, though) always have better performance / latency than Node.JS.

        However, with version 0.8 this has changed.
        Now I can’t always make a faster equivalent
        to a Node script in Java.
        Of 30 cases I have tried, only 7 cases had minor Java latency.

        The Google VM it uses (V8) is written in C, and it’s faster than Java because it compiles JS at run-time. (JIT)

  5. Hen says:

    Is it your opinion that Node.js is “way faster than Java for server related stuff” or do you have some evidence to backup your quite strong claim.

  6. Great guide man! I just got more interested in this World since I also came from Java background. Thanks!

  7. Good post and I hope you keep succeeding with Node.js. By the way, Node.js is not a language.

  8. Thanks ! I was really looking for a post like this for a while, I am also a Java Dev, and I also like to take a look at everything that comes up… I am also learning JS and Node.Js because it simply looks nice, but I was having a hard time to find frameworks and create a connection between what could be useful and what was noise ( this is a hard part of Node.JS too many frames for the same thing, it’s simply hard to choose.)

  9. TC says:

    Great post! Thanks!

  10. Anand says:

    Great post! What about security of web apps implemented using Node.js when compared to Java? Appreciate your insight.

    Thanks!

    ~Anand

    • matan says:

      If you’re looking for something similar to Spring Security or Apache Shiro, i’m not sure something exists exactly in that form (yet).

      Two popular options i’ve seen are everyauth (https://github.com/bnoguchi/everyauth) and passport (https://github.com/jaredhanson/passport).

      They don’t seem to to deal with authorization as much as authentication though. It’s definitely enough to build webapps including 3rd party authentication, and you can wire in your own authorization code as you see fit (roles, groups, etc).

  11. ubersoldat says:

    I found MongoDB the perfect couple with Node.js, but sometimes a no-sql database is not the best solution, that’s why I started a project called Jongo which tries to do what MongoDB REST service does, but using a JDBC backend.

    BTW, your blog doesn’t show on the iPad for some reason.

  12. […] From Java to Node.js « n0tw0rthy – […]

  13. fjunior87 says:

    Great Post!

    As I could understand you are going to use node.js for the new applications you will be working on. Do you think node.js is a good option for example if we are going to develop a system that consists basically in some CRUDs?

    Thanks,
    Junior

    • matan says:

      I think Node.js is a viable option for any type of dev to be honest. Of course it’s up to your personal preference to decide that for yourself.

      Regarding a CRUD app, those usually work well with a REST based model which is quite easy to build up in Node in a short amount of time.

  14. avinash says:

    Great post!!!i shared it on twitter

  15. […] Story: From Java to Node.js) Advertisement LD_AddCustomAttr("AdOpt", "1"); LD_AddCustomAttr("Origin", "other"); […]

  16. […] From Java to Node.js « n0tw0rthy På väg att ta steget till Node? Här är några tankar och länkar (via @ptz0n). […]

  17. […] found it on this blogpost and although there are some more links I found the object graph articles the most important […]

  18. […] Story: From Java to Node.js) Like this:LikeBe the first to like this post. java, node.js java, node.js Java tops list […]

  19. Is there a java framework that lets you build realtime apps with the same ease as Node?

  20. seo says:

    Woah! I’m really loving the template/theme of this blog. It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between user friendliness and visual appearance. I must say you have done a very good job with this. In addition, the blog loads extremely quick for me on Opera. Outstanding Blog!

  21. Jake says:

    Hello. What solutions have you found for DB transaction management?

  22. What happens to all other connected clients, if I put the one and only thread that node.js is able to use to a sleep for a while in my read event handling code, i.e. wait for a DB commit result? Do I stall the event handlers of all other clients?

    • matan says:

      Short answer is yes – if you do exactly what you described – which is some naive sleep in your code.

      However, if you keep everything evented (asynchronous) then you should be good.

      For example if your db driver is asynchronous (you get a callback on a successful commit) you don’t need to sleep at all. Your callback will continue the flow for that request.

      if your driver is synchronous, then you’ll need to do some extra work. First i’d try to find an asynchronous driver. There should be lots of them available. If not, consider process.nextTick() or setTimeout() if you really need to wait for something to complete. Those “share cycles” with other code waiting to be run like other event handlers.

      Hopefully that helps in some way.

  23. Thanks for enlighting me. I am still just stuck in the transaction pattern. I have to get use to ‘fire and forget and maybe correct myself later’ pattern… I am still so old school, BTW like my customers, when it comes to data durability an consitency…

    • matan says:

      I hear ya. But you don’t have to give up any of those things in Node.js. It just depends which data sources you are using.

      You can write a perfectly normal transactional CRUD app using Node.js.

  24. Quincy Wero says:

    Hi! This is kind of off topic but I need some guidance from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any tips or suggestions? Cheers

  25. About Java says:

    hi
    thanks for sharing this article..
    i’m fresher to java..
    informative for me.. :)

  26. dms says:

    What IDE do you use for node.js projects?

  27. upload says:

    Hello to every , as I am really keen of reading this website’s post to be updated on a regular basis. It consists of pleasant data.

  28. ken1077 says:

    Node.js is a runtime for Javascript, like Adobe Air is for Actionscript, like the JVM for Java. Every language and its runtime go through the same evolution, where they become more mature: optimized, faster, and have more 3rd party packages. Node.js is now just going through the same evolution the JVM had many many years ago. In time, it will be head-to-head with the JVM, possibly outperforms it in specific routines and perhaps trails in others. However, to think that node.js will significantly outperform the JVM, and make the choice of technology based on that, is not wise.

    Given comparably fast runtimes, the choice of whether to write your program in Javascript or in Java, really is about programming language rather than performance. A hand-coded ultra-optimized NIO implementation in Node will perform comparably with one in Java, because they both will translate to roughly the same underlying system routines being called. If one significantly under-performs another, just means it’s not ultra-optimized yet.

    In the end, it’s about whether you want loose-typing, closure, and prototype or you want uber-strict OOP. Javascript is surely shorter and easier to write; but the uber-strictness of Java is intentional. Strictness allows you to enforce paradigms and patterns, which is especially important in very large applications. Java has tons of enterprise experience; Javascript has a lot to prove itself.

    In summary, node.js simply allows Javascript to be an alternative to full-fledged programming languages for writing any kind of application, that’s all.

  29. I will immediately clutch your rss feed as I can’t find your email subscription hyperlink or e-newsletter service. Do you have any? Please allow me recognise so that I could subscribe. Thanks.

  30. Dhaval says:

    is it possible to do video conferencing with node.js with java? using applets?

  31. iOstroda says:

    You could definitely see your enthusiasm in the article you write.
    The sector hopes for even more passionate writers like you
    who are not afraid to say how they believe.
    All the time follow your heart.

  32. website says:

    hello there and thank you for your information – I’ve certainly picked up anything new from right here.
    I did however expertise a few technical points using this website,
    since I experienced to reload the website many times previous to I could get it to load properly.
    I had been wondering if your web host is OK? Not that I’m complaining, but
    sluggish loading instances times will often affect your placement in google and can damage your quality score if ads and marketing with
    Adwords. Well I am adding this RSS to my email and
    could look out for a lot more of your respective interesting content.
    Ensure that you update this again very soon.

  33. My boss at work is Node.js crazy. He has loads of former Java experience, but has glommed onto Node for many of the same reasons everyone always states, e.g. efficient asynchronous design, fast prototyping, great community, and how fast the V8 engine is. I tried some JS to make him happy, and saw how the APIs he was designing were lacking from a contract perspective, how bogged down my code became without natural and clear interfaces and subclasses, how much I missed dynamic proxies, annotations, and byte code modification. Cringing yet? Anyway, I took my bosses main queue-based service call distribution system and ported it to Java, normalizing it, allowing cross language calls, and side-band context passing in the process, which came naturally from the class hierarchy I had to develop around the transport. My boss picked it up and made the same changes to the JS version. We were both proud of what we’d done, and we just started load testing as well. So we each threw together a simple echo server, and had it load tested. The Java code, which I’ve been at for less time, has one fifth the latency and 5x the throughput. My boss has been crowing about the speed of Node this entire time. Fantasy meets reality. A lot of work has gone into Java. Yes it can be a total verbose pain. But a powerful one.

  34. jsnetwork says:

    Thanks for sharing your thoughts on jsnetwork. Regards

  35. julian says:

    what you think about http://ringojs.org ?

  36. kat says:

    I like the valuable information you provide in your articles.
    I’ll bookmark your weblog and check again here regularly.
    I am quite certain I will learn many new stuff right here!
    Best of luck for the next!

  37. I would really have a look at Vert.x: http://vertx.io/

    It brings the advantages of asynchronous, event-driven programming to Java, while leaving the disadvantages (IMHO a little chaotic language – JavaScript) behind.

    You get the performance and stability of JVM and also a nice syntax (with Java 8 and Lambdas, writing anonymous functions is in fact shorter than with JavaScript)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: