The biggest audience for my Node.js workshops, courses and books (especially when I’m teaching live) is Java developers. You see, it used to be that Java was the only language professional software developers/engineers had to know. Not anymore. Node.js as well as other languages like Go, Elixir, Python, Clojure, dictate a polyglot environment in which the best tool for the job is picked.

Node.js, which is basically a JavaScript run-time on the server, is getting more and more popular in the places where Java dominated because Node is fast and easy to setup. This post will help Java developers to transition to Node in a few short sections:

  • Node Terminology for Java Developer
  • Typing
  • Modules
  • Asynchronicity

Node Terminology for Java Developers

Since we have the luxury of assuming you are a Java developer, let’s define some Node terms using familiar Java names and concepts:

  • console.log('Hello') is System.out.print("Hello");
  • npm is Apache Maven (but bundled with Node)
  • npmjs.org is mvnrepository.com
  • Mongoose/Sequelize/Juggler/Waterline/Bookshelf is Hibernate: Persistence Object Relation/Document Mapper framework
  • Loopback is Spring MVC: MVC framework for web apps
  • Express middleware is Servlet filters: Code reuse for web apps
  • Atom/VS Code is Eclipse: Tools to write code
  • IntelliJ IDEA is Webstorm: Tools to write code developed by Jet Brains
  • Webpack/Grunt/Gulp is Ant/SBT/Gradle: Build tools (Node is interpreted so we do not compile into binary code, just to another source - transpilation)
  • Node non-blocking I/O is like NIO
  • MongoDB/PostgreSQL is like Oracle database
  • V8 is JVM
  • node debug is jdb: Command-line debugger
  • Node Inspector is JIVE: Visual debugger (GUI)
  • Node Foundation is Oracle Corporation (but non profit)
  • nvm/n/nave is jenv: Version manager
  • Mocha is junit
  • Winston is Jog4J

Bear in that these analogies were given just to speed up learning. They are not 100% accurate all the time. Some of the analogies are very stretched. For example, MongoDB is a NoSQL database while Oracle is mostly a SQL database.

Now once we are more or less aquatinted with the Node terminology, let’s look at some of the biggest differences between Node/JavaScript and Java, because these topics almost always come as questions during my live courses.

Entry point

Every Java (and generally, JVM) project has an entry point, which means the function that will be executed the very first moment the app is run by user and allocated in memory. In Node, entry point is the file passed to Node process:

node ./server.js

Node loads the content of server.js and interprets every statement, from top to bottom.

In Java, an entry point is typically a main method in a certain class. Node is way simpler and just interprets and builds up scope on the go. It doesn’t mean all the code will be executed right away. After all, function declaration doesn’t prescribe function execution. But it does mean that

console.log('Hello, World')

is a perfectly valid single-line Node application.

Typing

In Node/JavaScript, typing is loose. Each variable can hold any type of data so the value determines the current type not the variable itself. For example,

let str = 10
console.log(typeof str) // number
str = 'now, it is a string'
console.log(typeof str) // string

Similarly, in a function declaration we don’t set typing for the function arguments. For example, the argument page can be of a type number or function because its an optional argument:

const f = function (limit, page, callback) {
  if (typeof page == 'function' && !callback) {
    callback = page
    page = 1
  }
  // ...
  return callback()
} 
f(10, ()=>{}) // ok
f(10, 2, ()=>{}) // ok too

Modules

Modules in Node are local. Space is cheap, but time spent resolving conflicts between globally installed dependencies of multiple projects is precious. Java typically tries to put dependencies of a project into a global folder. Node and npm on the other hand, use a local subfolder node_modules. This way, each Node project can have any version of any module without causing any troubles to other projects.

Avoid installing anything globally, except maybe node-static or http-server (local development web servers for static content). Even tools like Webpack should go into local node_modules.

Good way to install a project dependency express:

npm i express

Bad way to install a global dependency express:

npm i -g express

Asynchronicity

Node is a non-blocking input/output platform which is great for building high performance apps. (Java has frameworks like Play or NIO to continue with analogies although frameworks are not the same as low level platforms because they tend to be more complex.)

It requires to shift thinking from synchronous to asynchronous way of coding. Instead of blocking code with requests, database or file reads/writes, in Node, developers harness the power of callbacks (with or without sugarcoating like Promises, async/await, etc.):

fs.writeFile('message.txt', 'Hello Node.js', (error) => { // could take a long time!
  // this function is executed as soon as writing file has been done, at unpredictable time in future
  if (error) console.error(error);
  console.log('It\'s saved!')
})
console.log('Started writing into file') // - this line is executed immediately after the previous one
// we didn't write yet.... come back on the next cycle

The mechanism which powers this non-blocking I/O in Node is called Event Loop. It’s taken straight from Google Chrome V8 engine which is used in the Chrome browser. Check out this article on how Event Loop works for more information.

Further Study

This is just a short introduction. For more information on Node, its patterns (including async) and best practices, follow these resources: