Backend

Node.js Essentials: 10 Core Concepts Every Developer Should Know

node.js
On this page
  1. 1. Running JavaScript with Node
  2. 2. Modules: CommonJS and ES modules
  3. 3. npm and package.json
  4. 4. The event loop and non-blocking I/O
  5. 5. Callbacks, promises and async/await
  6. 6. Built-in modules: fs, path and os
  7. 7. Events with EventEmitter
  8. 8. Streams
  9. 9. Environment variables
  10. 10. Handling errors without crashing
  11. Where to go next
  12. Putting it together: a tiny HTTP server without Express
  13. Testing with the built-in test runner
  14. Debugging Node.js properly
  15. Security basics every Node.js developer should know
  16. Choosing a Node.js version
  17. Common beginner mistakes
  18. Frequently asked questions
  19. Oh hi there 👋It’s nice to meet you.
  20. Sign up to receive awesome content in your inbox.

Node.js lets you run JavaScript outside the browser: on servers, in command-line tools and in build scripts. It is the “N” in MERN and the engine behind Express. These ten concepts cover most of what you need to read and write real Node.js code with confidence.

1. Running JavaScript with Node

// hello.js
console.log(`Hello from Node ${process.version} on ${process.platform}`);
node hello.js

There is no window or document in Node. Instead you get access to files, the network and the operating system. Use an even-numbered LTS (long-term support) version for real projects.

2. Modules: CommonJS and ES modules

Node supports two module systems. You will meet both:

// CommonJS (default in .js files without "type": "module")
const path = require('node:path');
module.exports = { add: (a, b) => a + b };

// ES modules (.mjs files, or "type": "module" in package.json)
import path from 'node:path';
export function add(a, b) { return a + b; }

For new projects, ES modules are the modern standard. The node: prefix makes it clear you are importing a built-in module, not an npm package.

3. npm and package.json

npm init -y                 # create package.json
npm install express         # add a dependency
npm install -D nodemon      # add a development-only dependency
npm ci                      # clean install from package-lock.json (use in CI and production)

Commit package-lock.json so everyone installs the exact same versions, and never commit node_modules. Add scripts to package.json, such as "dev": "node --watch server.js", and run them with npm run dev.

4. The event loop and non-blocking I/O

Node runs your JavaScript on one thread but hands slow work such as database queries and file reads to the system, so one server handles many users at once. The key rule: don’t block the thread with long synchronous work. The full explanation is in how Node.js handles thousands of requests on one thread.

5. Callbacks, promises and async/await

const fs = require('node:fs/promises');

async function readConfig() {
  try {
    const text = await fs.readFile('config.json', 'utf8');
    return JSON.parse(text);
  } catch (err) {
    console.error('Could not read config:', err.message);
    return {};
  }
}

Older Node APIs use callbacks such as (err, data) => {}. Most now have promise versions, like node:fs/promises. Prefer async/await in new code.

6. Built-in modules: fs, path and os

const path = require('node:path');
const fs = require('node:fs/promises');

const file = path.join(__dirname, 'data', 'users.json'); // safe on Windows, macOS and Linux
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, JSON.stringify([{ name: 'Aarav' }], null, 2));

Always build file paths with path.join() instead of gluing strings with slashes. In ES modules, use import.meta.dirname (Node 20.11 and newer) instead of __dirname.

7. Events with EventEmitter

const { EventEmitter } = require('node:events');

const orders = new EventEmitter();
orders.on('placed', (order) => console.log('Send email for order', order.id));
orders.emit('placed', { id: 101 });

Many Node objects, such as HTTP servers and streams, are event emitters. You attach listeners with .on().

8. Streams

Streams process data in chunks, so you can handle files and responses larger than your memory. They power file downloads, uploads and CSV exports. Learn them in Node.js streams: a practical guide.

9. Environment variables

// Node 20.6+ can load a .env file without any package:
//   node --env-file=.env server.js
const port = Number(process.env.PORT) || 5000;
const dbUrl = process.env.MONGODB_URI;

Keep secrets and per-environment settings in environment variables, not in your code.

10. Handling errors without crashing

An unhandled error crashes the whole Node process and takes every user’s request down with it. Catch errors where they happen, send them to one error handler in Express, and log anything unexpected:

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled promise rejection:', reason);
});

process.on('uncaughtException', (err) => {
  console.error('Uncaught exception, shutting down:', err);
  process.exit(1); // let PM2 or your platform restart a clean process
});

After an uncaught exception, the process may be in a broken state, so log it and restart rather than carry on.

Where to go next

With these basics, build a small Express API with MongoDB. Useful next reads: handling POST routes in Express, JWT authentication, and the Node.js production checklist.

Putting it together: a tiny HTTP server without Express

Express is built on Node’s own http module. Writing a small server without it once helps you understand what Express does for you, and it uses most of the concepts above in one file:

// server.js
const http = require('node:http');
const fs = require('node:fs/promises');
const path = require('node:path');

const PORT = Number(process.env.PORT) || 3000;
const notes = [{ id: 1, text: 'Learn the event loop' }];

const server = http.createServer(async (req, res) => {
  try {
    if (req.method === 'GET' && req.url === '/api/notes') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      return res.end(JSON.stringify(notes));
    }
    if (req.method === 'POST' && req.url === '/api/notes') {
      let body = '';
      for await (const chunk of req) body += chunk;           // the request is a stream
      const note = { id: notes.length + 1, text: JSON.parse(body).text };
      notes.push(note);
      res.writeHead(201, { 'Content-Type': 'application/json' });
      return res.end(JSON.stringify(note));
    }
    const html = await fs.readFile(path.join(__dirname, 'index.html'));
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
  } catch (err) {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Something went wrong');
  }
});

server.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`));

You can see what Express adds: routing by method and path, body parsing, JSON helpers, and error handling. Knowing the layer underneath makes Express errors much easier to understand.

Testing with the built-in test runner

Modern Node.js includes a test runner, so small projects don’t need any testing library at all:

// math.test.js
const test = require('node:test');
const assert = require('node:assert/strict');
const { add } = require('./math');

test('adds two numbers', () => {
  assert.equal(add(2, 3), 5);
});

test('rejects text', () => {
  assert.throws(() => add('2', 3), /numbers only/);
});

Run every test file with node --test. Add "test": "node --test" to your package.json scripts so npm test works in CI too. For larger projects, Vitest and Jest add watch mode, mocking helpers and nicer output, but the built-in runner is a great start.

Debugging Node.js properly

console.log takes you a long way, but a real debugger saves hours on tricky bugs. Start your app with the inspector:

node --inspect server.js        # attach a debugger at any time
node --inspect-brk server.js    # pause on the first line

Open chrome://inspect in Chrome and click your app to get the same DevTools you use for the browser: breakpoints, stepping through code, inspecting variables and the call stack. In VS Code, the JavaScript Debug Terminal does the same automatically for any command you run in it, including npm run dev.

Security basics every Node.js developer should know

  • Never trust input. Validate request bodies, query strings and headers before using them. Don’t pass user input straight into database queries, file paths or shell commands.
  • Avoid running shell commands with user input. If you must use child_process, prefer execFile with an array of arguments over exec with a string.
  • Keep dependencies updated and check them with npm audit. Most real-world vulnerabilities come from outdated packages.
  • Don’t commit secrets. Keep .env in .gitignore, and if a key is ever pushed, rotate it immediately, even if you delete the commit.
  • Don’t use eval or new Function with any data that comes from users.

Choosing a Node.js version

Node.js releases a new major version every six months. Even-numbered versions become LTS (long-term support) and receive fixes for about three years, which makes them the right choice for production. Odd-numbered versions are short-lived and best for trying new features. Check which versions are in active LTS on the official Node.js release schedule before starting a project, and pin the version for your team with an .nvmrc file or the engines field in package.json:

{
  "engines": { "node": ">=22" }
}

A version manager such as nvm (macOS and Linux), nvm-windows or fnm lets you switch between versions per project with one command, which helps when an older project needs an older Node.js.

Common beginner mistakes

  • Forgetting await. Without it you get a pending Promise instead of the data, often printed as Promise { <pending> }.
  • Mixing require and import in one file. Choose one module system per project, or use .mjs and .cjs extensions deliberately.
  • Using relative paths from the wrong folder. fs.readFile('./data.json') is relative to where you run Node, not where the file is. Use path.join(__dirname, 'data.json').
  • Installing packages globally that belong to the project. Project tools go in devDependencies and run through npm scripts or npx.

Frequently asked questions

Is Node.js a language or a framework?

Neither. Node.js is a runtime: a program that runs JavaScript outside the browser. Express is a framework built on top of it.

Should I use require or import?

For new projects, use ES modules with import. Many existing projects and tutorials use require, so it is worth being comfortable with both.

Do I need nodemon?

Not anymore for simple projects. node --watch server.js restarts your app when files change.

How long does it take to learn Node.js?

If you already know JavaScript, a few weeks of building small projects covers the essentials in this guide. Production skills such as security, testing and deployment come with practice on real projects.

logo

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Saurabh Pathak

Saurabh Pathak is an AI engineer and MERN stack developer, and the founder of mernstackdev.com. He builds open-source projects such as the Haat gateway and MCP safety tooling, and he writes hands-on tutorials on React, Node.js, MongoDB and AI agents. He cares most about code that works in production.