Home

Node.js

Install Nodejs on Linux

Method without Node Version Manager

1. sudo apt update
2. sudo apt upgrade
3. sudo apt install curl
4. curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
5. sudo apt install nodejs

# Check for success:
node -v and npm -v

Node Package Manager (npm)

Show version

npm -v or npm --version

List installed packages (in current folder, without package name to list all)

npm list <package name>

List globally installed packages

npm list -g <package name>

List all globally installed packages and their dependencies

npm list -g

List only the global installed packages without their dependencies

npm list -g --depth=0

Locate the cache directory (The cache is constantly growing and should be cleared from time to time)

npm config get cache

Verify content of the cache folder and garbage collect unneeded data

npm cache verify

Manually clear the cache

npm cache clean --force

Node Version Manager

Installation

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash

or

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash

Check version of nvm

nvm --version

Get list of available node versions

nvm ls-remote

Get list of installed node versions

nvm ls

Install node with nvm

  • Note: NVM installs Node.js in a user-specific directory
  • It does not affect the system-wide configuration

nvm install node

Install latest LTS release of node

nvm install --lts

Install specific version of node

nvm install 17.0.1 # specific minor release
# or
nvm install 19 # specific major release only

Use specific version of node

# Permanently

nvm alias default < number >
# or
nvm alias default node # selects latest version

# For one shell session

nvm use < number >
# or
nvm use node # selects latest version

Cookies

Version 1: (setting the Set-Cookie header in the response)

res.header('Set-Cookie', 'sessionId=abc123; Expires=Wed, 31 Oct 2028 13:37:00 GMT; Secure; HttpOnly')

Version 2: (Express-specific, automatically handles Set-Cookie header creation)

res.cookie('SessionId', 'xyz987', { expires: new Date(Date.now() + 900000), secure: true, httpOnly: true })

Options:

// Specific expiration Date
expires=Thu, 18 Dec 2013 12:00:00 UTC

 // Maximum age in ms from cookie creation date (10s)
maxAge:10000

// Domain for which the cookie is valid, default is where it was created
domain: 'example.com'

// Defines the URL path that must exist in the requested URL (default is "/")
path: '/myPath'
 
// Cookie is sent only over HTTPS connections (exception for localhost but not from thunder client, etc.)
secure: true

// Makes the cookie inaccessible to JavaScript's document.cookie. Mitigating XSS attacks
httpOnly: true

// Controls whether the cookie is sent with cross-site requests. (Options: strict, lax, none)
// strict: not sent with requests initiated by third-party websites
// lax: sent by top level requests, not by cross-site requests (e.g., loading images, iframes, or scripts)
// none: cookie is sent with all requests
sameSite: 'lax'

Make cookies available in the req.cookies object

npm i cookie-parser

app.use(cookieParser());

Deleting cookie (set expires to the past or maxAge to 0)

res.cookie('name', '', { expires: new Date(0) });

or

res.cookie('name', '', { maxAge: 0 });

Importing json

const user = require("./data.json")

or

const user = require("./data")

From Node js version 16.18.1 and up (only default export supported)

Importing by using the keyword import

In package.json

1. "type": "module"

In Server js

2. import data from "./data.json" assert {type: "json"}

Importing json from js file with import

In data file

1. export default [ {...}, {...}, {...} ]

In package.json

2. "type": "module"

In server.js

3. import data from "./data.js"

The filesystem object (fs)

Write/append/read the asynchronous way

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

Writing file

async function writeFile(filename, content) {
    try {
        await fs.writeFile(filename, content);
        console.log("Datei wurde erfolgreich erstellt!");
    } catch (err) {
        console.log("Fehler beim schreiben der Datei:", err);
    }
}

Appending file

async function appendFile(filename, content) {
    try {
        await fs.appendFile(filename, content);
        console.log("Datei wurde erfolgreich erweitert!");
    } catch (err) {
        console.log("Fehler beim erweitern der Datei:", err);
    }
}

Reading file

async function readFile(filename) {
    try {
        const data = await fs.readFile(filename, 'utf8');
        console.log("Dateiinhalt:", data);
    } catch (err) {
        console.log("Fehler beim Lesen der Datei", err);
    }
}

Function calls

async function main() {
    try {
        await writeFile("test.txt", "Irgendein beliebiger Text\n");
        await appendFile("test.txt", "Noch mehr beliebiger Text\n");
        await readFile("test.txt");
        console.log("Alle Operationen wurden erfolgreich abgeschlossen.");
    } catch (error) {
        console.error("Ein Fehler ist aufgetreten:", error.message);
    }
}

main();

Write/append/read the synchronous way

const fs = require("fs");

Writing file

function writeFileSync(filename, content) {
    try {
        fs.writeFileSync(filename, content);
        console.log("Datei wurde erfolgreich erstellt!");
    } catch (err) {
        console.log("Fehler beim Schreiben der Datei:", err);
    }
}

Appending file

function appendFileSync(filename, content) {
    try {
        fs.appendFileSync(filename, content);
        console.log("Datei wurde erfolgreich erweitert!");
    } catch (err) {
        console.log("Fehler beim Erweitern der Datei:", err);
    }
}

Reading file

function readFileSync(filename) {
    try {
        const data = fs.readFileSync(filename, 'utf8');
        console.log("Dateiinhalt:", data);
        return data;
    } catch (err) {
        console.log("Fehler beim Lesen der Datei:", err);
        return null;
    }
}

Function calls

writeFileSync("test.txt", "Irgendein beliebiger Text\n");
appendFileSync("test.txt", "Noch mehr beliebiger Text\n");
const content = readFileSync("test.txt");

Debugging

In The Browser

Type “debugger” in the code of the file to inspect (debugger will pause at that line)

Start debugger in the terminal

node --inspect <filename>

In the chrome URL

chrome://inspect

In the chrome window click on

Open dedicated DevTools for Node

Options

--inspect (Pauses execution if it hits a debugger statement)
--inspect-brk (Pauses execution immediately when node starts)
--inspect-wait (Will wait for debugger to be attached before executing the code)

In VSCode

For backend project stop server from running

1. Open new terminal with: "JavaScript Debug Terminal" (click on arrow next to plus icon on the bottom right)
2. Run file (e.g. for server: npm start)
3. Set breakpoint(s) in file to be examined (klick next to line number or type "debugger")
4. In a Router: make a request, code will stop to execute at the breakpoint

Alternative (no new terminal, server can be running)

1. Open debugger from the left sidebar
2. Click on the cog wheel to open the launch.json file
3. Click on the "Add Configuration" button at the bottom
4. Choose "{}Node.js: Attach to Process"

Example launch.json (only the value under "programm" would need to be adapted)
{
"configurations": [
    {
        "name": "Attach by Process ID",
        "processId": "${command:PickProcess}",
        "request": "attach",
        "skipFiles": [
            "/**"
        ],
        "type": "node"
    },
    {
        "name": "Launch backend Program",
        "program": "${workspaceFolder}/05-BE/06-status-codes-error-handling/backend/server.js",
        "request": "launch",
        "skipFiles": [
            "/**"
        ],
        "type": "node"
    },
]
}

5. Set the breakpoints and run the script (the value of the "name" key is the file name)
6. Choose one of the options that pop up after runnng the script (e.g. node server.js) to start debugging

Environment Variables

For node Versions 20+

In package.json

We need to tell nodejs where our .env file is located (here at level of the package.json)

"start": "node --env-file=.env server.js"

In .env

PORT=3000
USER_KEY=029374ewoiurew

In .env.sample

PORT=
USER_KEY=

Where the variables are needed

const PORT = process.env.PORT;
const USER_KEY = process.env.USER_KEY;

For node Versions before 20

Install dotenv package

npm i dotenv

Were the variable is needed

import dotenv from "dotenv";
dotenv.config();

//or
import 'dotenv/config';

const PORT = process.env.PORT;

or for common js

require("dotenv").config();

const PORT = process.env.PORT;

__dirname & __filename

For ES modules

Since Node.js version 20.11.0, Deno version 1.40.0 and Bun version 1.0.23

import.meta.dirname  // The current module's directory name
import.meta.filename // The current module's file name

For older versions

import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

or

import * as url from 'url';

const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
const __filename = url.fileURLToPath(import.meta.url);

For commonJs

No import or configuration needed since variables are already available

__dirname  // The current module's directory name
__filename // The current module's file name