JAVASCRIPT

Node.js: Syntax, Usage, and Examples

Node.js is a JavaScript runtime that lets you run JavaScript outside the browser, most often on a server. It’s widely used to build APIs, web apps, and tools that run from the command line.


How to Use Node.js

You don’t write “Node.js code” with special syntax. You write JavaScript, then run it with Node.

Running a file with Node

Create a file called app.js:

console.log("Hello from Node!");

Run it in your terminal:

node app.js

Node reads the file, executes it, and prints the output.

Importing and exporting code

Modern Node supports ES modules in many setups, but CommonJS is still common in a lot of projects. You’ll run into both.

CommonJS (very common in older projects)

// math.js
functionadd(a, b) {
return a + b;
}

module.exports = { add };

// app.js
const { add } =require("./math");

console.log(add(2,3));

ES modules (common in newer projects)

// math.js
exportfunctionadd(a, b) {
return a + b;
}

// app.js
import { add }from"./math.js";

console.log(add(2,3));

If you ever feel like your imports “randomly don’t work,” it’s usually because the project is using a different module style than you expected.

Reading input from the terminal

Node is great for scripts. One simple example is reading command-line arguments.

const name = process.argv[2] ||"friend";
console.log(`Hello, ${name}!`);

Run it like this:

node app.js Maya

Now your script can react to input without a browser.

Creating a basic web server

Node can handle HTTP requests directly. This example uses the built-in http module:

const http =require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, {"Content-Type":"text/plain" });
  res.end("Hello from the server!");
});

server.listen(3000,() => {
console.log("Server running on http://localhost:3000");
});

Open http://localhost:3000 in your browser and you’ll see the response.

This works, but most real apps use a framework like Express so you don’t have to manually handle every detail.


When to Use Node.js

Node fits a lot of real-world work, especially when you want JavaScript across the whole stack.

1) Building backend APIs

Node is often used for REST APIs and GraphQL servers. You can handle requests, validate data, talk to a database, and send responses back to a frontend app.

Common API use cases:

  • user sign-up and login
  • product search and filtering
  • saving comments or likes
  • payments and subscriptions

2) Creating real-time features

Node handles many connections efficiently, which makes it a good match for real-time apps.

Examples:

  • chat apps
  • live notifications
  • multiplayer game updates
  • collaborative editing tools

3) Writing automation scripts and developer tools

Node can do more than servers. It’s also great for scripts.

You can:

  • rename files in a folder
  • generate reports
  • validate JSON files
  • download and process data from an API
  • build your own CLI tool

If you ever thought, “I wish I could automate this boring task,” Node is a solid option.

4) Server-side rendering and full-stack JavaScript apps

Many frameworks use Node behind the scenes to render pages, build bundles, and handle backend routes. That includes tools like Next.js and others that combine frontend and backend work.


Examples of Node.js

Let’s walk through a few simple examples that show what Node is good at.

Example 1: Create a tiny API endpoint

Here’s a small Express server that returns JSON. Express is popular because it makes routing simple.

const express =require("express");
const app =express();

app.get("/api/status",(req, res) => {
  res.json({status:"ok",time:newDate().toISOString() });
});

app.listen(3000,() => {
console.log("API running on http://localhost:3000");
});

If you visit /api/status, you’ll get a JSON response. This is the foundation of many backend apps.


Example 2: Read and write a file with fs

Node includes a built-in module called fs for working with files.

const fs =require("fs");

fs.writeFileSync("note.txt","Remember to drink water ✅");
const savedNote = fs.readFileSync("note.txt","utf8");

console.log(savedNote);

This is useful for:

  • saving logs
  • generating static files
  • reading configuration files
  • creating build scripts

Example 3: Fetch data from an API

Modern Node supports fetch() in newer versions, but many projects still use libraries like Axios. Here’s an example with fetch():

asyncfunctionloadUser() {
const response =awaitfetch("https://api.github.com/users/octocat");
const data =await response.json();

console.log(data.login);
}

loadUser();

You can use this pattern to:

  • pull weather data
  • sync a spreadsheet
  • connect services together
  • build a backend that talks to other APIs

Example 4: A simple CLI “task list” tool

Here’s a tiny script that lets you add tasks from the terminal.

const fs =require("fs");

const task = process.argv.slice(2).join(" ");

if (!task) {
console.log("Add a task like: node tasks.js Buy eggs");
  process.exit(0);
}

fs.appendFileSync("tasks.txt", task +"\n");
console.log("Task added ✅");

This is the kind of thing you’d build when you want quick automation without building a full app.


Learn More About Node.js

Node has a few key concepts that show up all the time, especially when you move past basic scripts.

The event loop and async code

Node is built around asynchronous programming. That means it can start a task, move on to something else, then come back when the task finishes.

A common example is reading a file asynchronously:

const fs =require("fs");

fs.readFile("note.txt","utf8",(err, data) => {
if (err) {
console.log("Something went wrong:", err.message);
return;
  }

console.log("File contents:", data);
});

console.log("This prints first!");

The last line runs before the file finishes reading, because the file read happens in the background.

This style can feel strange at first, but it’s one of the reasons Node scales well when many users connect at once.

Promises and async/await

Promises make async work easier to manage. async/await makes it even cleaner.

Here’s a file read using promises:

const fs =require("fs").promises;

asyncfunctionreadNote() {
const text =await fs.readFile("note.txt","utf8");
console.log(text);
}

readNote();

Once you get comfortable with async/await, a lot of Node code becomes much easier to follow.


Working with packages using npm

Most Node projects use npm to install libraries.

Common commands:

  • npm init creates a new project
  • npm install express installs Express
  • npm install -D nodemon installs a dev tool as a dependency for development

When you install packages, they appear in:

  • node_modules/
  • package.json

If your project breaks after cloning it, missing dependencies are often the reason. Running npm install usually fixes it.


Environment variables and configuration

Real apps should not hardcode secrets like API keys. Node apps often use environment variables instead.

const apiKey = process.env.API_KEY;

if (!apiKey) {
console.log("Missing API_KEY in environment variables.");
}

This is also how you set ports, database URLs, and feature flags without changing code.


Node and databases

Node works with all common database types.

Examples include:

  • PostgreSQL for relational data
  • MongoDB for document-style data
  • Redis for caching and sessions

Most database work in Node follows the same pattern:

  1. connect
  2. query or update data
  3. handle errors
  4. return a result

Common “gotchas” beginners hit

Node is beginner-friendly, but a few things trip people up:

Mixing module systems

require() and import are not interchangeable. Stick to the style your project uses.

Forgetting to return a response

In server code, if you don’t send a response, requests hang and your app feels broken.

Async errors disappearing

Errors inside async code need proper handling, usually with try/catch and .catch().

Example:

asyncfunctionloadData() {
try {
const res =awaitfetch("https://example.com/data");
const data =await res.json();
console.log(data);
  }catch (error) {
console.log("Request failed:", error.message);
  }
}

loadData();


Summary

Node.js lets you run JavaScript outside the browser, which makes it great for backend APIs, real-time apps, automation scripts, and developer tools. You write normal JavaScript, run it with node, and use modules like fs and http to work with files and servers. Once you add npm packages, async patterns, and a framework like Express, you can build full production apps using the same language you already use on the frontend.