Skip to main content

Node.js

  • Node.js is an open source server environment
  • Node.js uses JavaScript on the server
  • Node.js runs single-threaded, non-blocking, asynchronous programming
  • Node.js can
    • Generate dynamic page content
    • Create, open, read, write, delete, and close files on the server
    • Collect form data
    • Add, delete, modify data in database
  • npm is the standard package manager for Node.js

Basic commands

> node --version
> node file.js
> npm install <package-name><@version> <--save-dev>
> npm i <package-name>@latest <-D>

> npm update <package-name>
> npm start
> npm run <task-name>
> npm run start-dev
{
"scripts": {
"start-dev": "node lib/server-development",
"start": "node lib/server-production"
}
}

Modules

// myFirstModule.js
exports.myDateTime = function () {
return Date();
};
// { myDateTime: func }

// other file
const dt = require("./myFirstModule");
console.log(dt.myDateTime());

Built-in modules

ModulesFor
asserttest
bufferbinary data
child_processesrun a child processes
clustersplit single Node process -> multiple
cryptohandle OpenSSL cryptographic func
dnsDNS lookups & name resolution func
eventsassign and trigger events
fshandle file system
httpNode.js act as an HTTP server
httpsNode.js act as an HTTPS server
netcreate servers & clients
osProvides information about operation system
pathhandle file path
querystringhandle URL query string
readlinereadable streams one line at the time
streamhandle streaming data
string_decoderdecode buffer objects to strings
timersTo execute a function after a given number of milliseconds
tlsimplementing TLS (Transport Layer Security) and SSL (Secure Socket Layer)
urlparse URL strings
utilutility functions
vmcompile js code in a virtual machine - like eval() in js
zlibcompress or decompress files

HTTP

var http = require("http");
var url = require("url");

http
.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/html" });
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt); // Add to body
})
.listen(8080);

// http://localhost:8080/?year=2017&month=July -> "2017 July"

Testing

import assert from "node:assert";
import test from "node:test";

test("that 1 is equal 1", () => {
assert.strictEqual(1, 1);
});
test("that throws as 1 is not equal 2", () => {
// throws an exception because 1 != 2
assert.strictEqual(1, 2);
});

Read & Hash a file

import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";

const hasher = createHash("sha1");
hasher.setEncoding("hex");
// ensure you have a `package.json` file for this test!
hasher.write(await readFile("package.json"));
hasher.end();
const fileHash = hasher.read();

Stream pipeline

import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";

// ensure you have a `package.json` file for this test!
await pipeline(
// 🤔
createReadStream("package.json"),
createGzip(),
createWriteStream("package.json.gz")
);

Threads

import {
Worker,
isMainThread,
workerData,
parentPort,
} from "node:worker_threads";

if (isMainThread) {
const data = "some data";
const worker = new Worker(import.meta.filename, { workerData: data });
worker.on("message", (msg) => console.log("Reply from Thread:", msg));
} else {
const source = workerData;
parentPort.postMessage(btoa(source.toUpperCase()));
}

How to keep packages up-to-date

Install npm-check-updates

npm install -g npm-check-updates

Scan packages (You can repeat this step)

ncu -u

Update packages (use npm or yarn)

npm install
When to use Module, CommonJS, Class
  • Use ES Modules (import/export) for modern projects, especially if targeting both browser and Node.js environments, or if you want to use the latest JavaScript features.
  • Use CommonJS (require/module.exports) for backward compatibility or if working with older Node.js projects and libraries.
  • Use classes in JavaScript when:
    • You need to encapsulate data and behavior together (OOP).
    • You are building complex, reusable objects with inheritance or polymorphism.
    • In frameworks like React, where class components are used (though functional components are now more common).

For simpler tasks or functional programming, avoid classes and opt for regular functions or objects.

Resources

  1. Node.js Documents (20.x)
  2. w3schools - Node.js