All posts

6 min read

Java developer learning Node.js: what carries over, what's new, 30-day plan

Practical guide for Java devs to transition to Node.js, covering transferable skills, new concepts, pitfalls, a 30‑day roadmap, and quick FAQ.

What carries over

Java conceptNode.js equivalentHow it helps you transition
Object‑oriented designYou can still use classes (class Foo {}) and inheritance (extends) introduced in ES6.Your mental model of encapsulation, interfaces (via TypeScript or JSDoc), and SOLID still applies.
Static typing (optional)Flow/TypeScript or JSDoc can give you compile‑time checks.If you prefer staying typed, add a tsconfig.json and write .ts files; the compiler will catch many of the same mistakes you know from javac.
Package managementnpm / yarn vs Maven/Gradle.The idea of a central repository, version constraints, and a lock file (package-lock.json) mirrors pom.xml and gradle.lockfile.
Build & test lifecycleScripts in package.json (npm test, npm run build) replace Maven phases.You already know the value of clean, compile, test, package; just map them to npm scripts.
Dependency injection patternsManual DI or libraries like awilix, inversify.The pattern of constructor injection, singletons, and scopes works the same; you just use JavaScript functions or decorators.
Loggingconsole, winston, pino vs java.util.logging or Log4j.Structured logging concepts (levels, transports) are identical; only the API differs.
Exception handlingtry/catch/finally works the same; async errors use catch on Promises.Your habit of catching checked exceptions translates to catching rejected Promises.
Unit testingjest, mocha vs JUnit.Test suites, assertions, mocks, and coverage tools are conceptually the same.
RESTful API designExpress/Koa vs Spring MVC.Routing, request/response objects, middleware pipelines map directly to controllers and filters.
Concurrency mindsetEvent loop + async/await vs threads & executors.Understanding that you must avoid blocking operations is the same discipline; just use non‑blocking APIs.

What's new

Example: reading a file and printing its size

Java (using NIO)

import java.nio.file.Files;
import java.nio.file.Path;

public class FileSize {
    public static void main(String[] args) throws Exception {
        Path path = Path.of("example.txt");
        long size = Files.size(path);
        System.out.println("Size: " + size);
    }
}

Node.js (using the promises API)

// fileSize.mjs
import { stat } from 'fs/promises';

async function printSize() {
  try {
    const { size } = await stat('example.txt');
    console.log(`Size: ${size}`);
  } catch (err) {
    console.error('Error:', err);
  }
}

printSize();

What changed and why

  • Module system – Java uses the classpath; Node.js now prefers ES modules (import … from). CommonJS (require) still works but ES modules are the modern default.
  • I/O model – Java’s Files.size is blocking; Node.js’s fs/promises.stat returns a Promise, encouraging non‑blocking code.
  • Error handling – Checked exceptions disappear; you handle runtime errors with try/catch around await.
  • Entry point – No public static void main; the script runs top‑to‑bottom, and you explicitly invoke the async function.

Other new concepts

  • Event loop – All JavaScript runs on a single thread; long‑running CPU work must be off‑loaded to worker threads or native addons.
  • Callback‑centric APIs – Many core modules expose both callback and Promise forms; prefer the Promise version for readability.
  • Package.json scripts – npm run dev replaces Maven’s mvn spring-boot:run.
  • Environment variables – process.env is the canonical way to read configuration; no System.getenv wrapper needed.

Common pitfalls

PitfallWhy it trips Java devsHow to avoid it
Blocking the event loopAssuming a method like fs.readFileSync is harmless.Use async APIs (fs.promises) or move CPU‑heavy work to a worker thread (worker_threads).
Implicit type coercionJava’s strict typing hides subtle conversions.Enable strict mode ("use strict";) and consider TypeScript or JSDoc for static checks.
Global variablesvar hoisting can create hidden state.Use let/const and keep everything inside modules.
Forgotten awaitMissing await returns a Promise instead of the value, leading to “undefined”.Lint with eslint rule no-floating-promise and always assign the result of an async call to a variable after await.
Package version driftnpm install may pull newer minor versions that break code.Commit package-lock.json and use npm ci in CI pipelines.
Misunderstanding thisArrow functions bind lexical this; regular functions do not.Remember that class methods defined as method() {} get their own this, while callbacks often need arrow functions.
Error propagation in async codeThrowing inside a Promise without a catch silently fails.Always attach .catch or wrap async code in try/catch.
Mixing ES modules and CommonJSImporting a CommonJS module with import can give a default object wrapper.Stick to one module system per project; if you need both, use dynamic import() for CJS.

Your 30‑day plan

Week 1 – Foundations

  1. Install Node.js (LTS) and npm. Verify with node -v and npm -v.
  2. Initialise a project: npm init -y. Examine package.json.
  3. Write three tiny scripts:
    • Hello world (console.log).
    • Read a file asynchronously (fs/promises).
    • Simple HTTP server with the built‑in http module.
  4. Mini‑project: Build a CLI tool that accepts a file path argument and prints the number of lines (process.argv, readline).

Week 2 – Web layer & tooling

  1. Install Express: npm i express. Scaffold a basic REST endpoint (GET /hello).
  2. Add nodemon as a dev dependency (npm i -D nodemon) and create an npm script "dev": "nodemon index.mjs".
  3. Set up ESLint with the recommended config (npm i -D eslint → npx eslint --init).
  4. Mini‑project: Implement a CRUD API for an in‑memory “Todo” list (GET, POST, PUT, DELETE). Write unit tests with Jest (npm i -D jest).

Week 3 – Asynchrony, data, and type safety

  1. Explore async/await deeper: parallel vs sequential (Promise.all).
  2. Add a database driver (e.g., npm i pg for PostgreSQL). Write a simple query using the promise API.
  3. Introduce TypeScript: npm i -D typescript @types/node. Run npx tsc --init and rename files to .ts.
  4. Mini‑project: Extend the Todo API to persist data in PostgreSQL, using async/await and typed models.

Week 4 – Production readiness

  1. Add a logger (npm i pino). Replace console.log with structured logs.
  2. Implement graceful shutdown: listen for SIGINT/SIGTERM, close server and DB pool.
  3. Containerise the app: write a minimal Dockerfile (FROM node:lts, COPY, RUN npm ci, CMD ["node", "dist/index.js"]). Build and run locally.
  4. Capstone project: Combine everything – a typed, logged, Docker‑ready Todo service with unit tests and a simple CI script (npm test && npm run lint).

FAQ

How do I debug a Node.js app?

Use the built‑in inspector: start with node --inspect-brk index.mjs and open chrome://inspect in Chrome, or use VS Code’s “Attach” debugger configuration.

Should I use CommonJS or ES modules?

Prefer ES modules (.mjs or "type": "module" in package.json) for new code; they align with the JavaScript standard and work seamlessly with import.

Is TypeScript required for a Java background?

Not required, but adding TypeScript gives you compile‑time checks similar to Java’s compiler and can smooth the transition.

How do I manage environment‑specific configuration?

Store values in .env files and load them with the dotenv package (require('dotenv').config()), then access via process.env.VAR_NAME.

Keep going

#java #nodejs #learning #guide