LESSON 69 · ADVANCED4 min read

Node.js Runtime & npm

Move JavaScript to the server, organise a project with modules and npm scripts, and load configuration without hard-coding secrets.

ES2024 / Node.js 20+Free to readModule 16 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Compare the browser and Node.js execution environments.
  • Choose between CommonJS and ES modules and configure package.json correctly.
  • Use npm scripts, environment variables, and file-system APIs in a small project.

01One language, two runtimes

Browser JavaScript and Node.js share the language but not the environment. A browser gives you window, the DOM, localStorage, and a rendering pipeline. Node gives you process, the file system, network sockets, and no DOM at all. Code that manipulates a page cannot run unchanged on the server, and code that reads files is unavailable in a normal browser tab.

Node runs the V8 engine outside the browser and adds host APIs through built-in modules. The same language skills transfer, but the globals and the security model do not. Before reaching for a browser API on the server, check whether Node exposes an equivalent under the node: prefix. A server also has different risks: every request may be hostile, and nothing is hidden in a client bundle.

src/inspect.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Modules: CommonJS and ES modules

Older Node projects use CommonJS: require loads a module and module.exports exposes values. Modern Node supports ES modules with import and export, top-level await, and explicit file extensions. Setting "type": "module" in package.json makes .js files ESM; without it, Node treats .js as CommonJS unless configured otherwise.

You can consume packages that use either style, but choose one module system for your own source. ESM imports are static, so tooling can analyse dependencies before execution; CommonJS loads synchronously at runtime. Use node: prefixes such as node:fs/promises to make built-ins unmistakable and to avoid clashing with package names.

Relative imports in ESM need a file extension, so write ./store.js, not ./store; a directory import needs an explicit index.js. Package imports such as express resolve through node_modules. This strictness is useful: the same specifier works in Node and in browser module loaders without a bundler guessing what you meant.

src/math.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03package.json, dependencies, and scripts

package.json names the project, declares its module type, lists dependencies, and defines scripts. dependencies are needed at runtime; devDependencies are tools used only during development, such as test runners or linters. Install with npm install and commit the lockfile so every machine resolves the same versions.

Scripts turn long commands into short, discoverable ones: npm run dev can start a watcher, npm start can run the server, and npm test can run the test suite. Node's built-in --watch flag restarts a process after a file change, which removes the need for a separate development dependency in small projects.

Run npm install once after cloning, then use the scripts for daily work. Commit package-lock.json; it records the exact dependency tree so a teammate or deployment server does not resolve a different minor version.

package.jsonJSON
{  "name": "bookstore-api",  "version": "1.0.0",  "private": true,  "type": "module",  "scripts": {    "start": "node src/server.js",    "dev": "node --watch src/server.js",    "test": "node --test"  },  "dependencies": {    "express": "^5.1.0"  }}
Outputstdout
npm run dev starts the server and restarts it after each saved change.

04Environment variables and project paths

Configuration belongs in environment variables, not in source code. Read process.env.PORT and provide a safe default; never commit API keys or database passwords. Node can load a .env file with --env-file=.env, but the file itself must stay out of version control. Document every required variable so another developer can start the project.

Use node:path and node:url to build paths instead of concatenating strings. import.meta.url locates the current module, which is more reliable than process.cwd() when a process is started from another directory. Keep a small structure: src/ for code, data/ for local fixtures, and one entry point that wires the pieces together.

src/config.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Node shares JavaScript with the browser but replaces DOM APIs with server-side host APIs.
  • Choose one module system, set the package type explicitly, and use node: imports for built-ins.
  • Keep configuration in environment variables and resolve paths relative to the module, not the shell.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Create a configuration module

Write src/config.js that exports a frozen object with a numeric port from PORT (default 3000), a dataDir resolved relative to the module, and a nodeEnv from NODE_ENV (default development).

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
import path from "node:path";import { fileURLToPath } from "node:url";const here = path.dirname(fileURLToPath(import.meta.url));export const config = Object.freeze({  port: Number(process.env.PORT ?? 3000),  dataDir: path.join(here, "..", "data"),  nodeEnv: process.env.NODE_ENV ?? "development",});

import.meta.url gives the module's own location, so dataDir does not depend on where the process was started. Object.freeze prevents accidental reassignment, and Number converts the environment string to the type the server expects.

02

Exercise 2: Read a file with a safe fallback

Write an async function readJson(file, fallback) that returns parsed JSON, returns the fallback when the file does not exist, and lets other errors such as invalid JSON propagate.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
import { readFile } from "node:fs/promises";export async function readJson(file, fallback) {  try {    return JSON.parse(await readFile(file, "utf8"));  } catch (error) {    if (error.code === "ENOENT") return fallback;    throw error;  }}

Only a missing file is treated as an expected condition. A syntax error from JSON.parse or a permission error still rejects, so a damaged data file is not silently replaced with an empty value.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Which global is available in Node.js but not in a normal browser page?
02Where should a test runner be listed in package.json?
03What does "type": "module" in package.json change?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Create a configuration module

Write src/config.js that exports a frozen object with a numeric port from PORT (default 3000), a dataDir resolved relative to the module, and a nodeEnv from NODE_ENV (default development).

main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.