Node.js
What Node.js is: the engine from Chrome with your computer around it in place of a page. The REPL, the process object, the core modules (fs for files, path, streams, and http for a server built from one function), how the event loop and non-blocking I/O let a single thread serve many requests, and installing a package with npm.
In this lesson
This lesson builds a web server in JavaScript, running on Node. Send it ten thousand requests at the same moment, and every one of them gets an answer. Yet Node runs your JavaScript on a single thread, which means one piece of code at a time. So how does one thread keep up with ten thousand visitors?
By the end of this lesson you’ll know what Node is and how to try code at its prompt. You’ll read and write files, build paths that work from any folder, and write a server with nothing but the modules Node comes with. And you’ll know how that server handles many requests on one thread: the event loop, plus non-blocking I/O.
What Node is
Inside Chrome there’s an engine called V8. It reads JavaScript and runs it: values, functions, classes, promises. That is the language, and V8 knows nothing beyond it. It has never seen a page or a network, and it can’t even set a timer.
Everything else is handed in by the program the engine sits inside, which is called a runtime. Chrome is one runtime. It hands the engine a page: document, window, buttons, storage. Node is another, first released in 2009 and built around the same engine. It hands over the computer instead: its files, its network, and the running program itself. A few things both runtimes supply, each in its own way: console, timers such as setTimeout, and fetch. None of those three is in the language’s specification. Deno and Bun are two more runtimes.
So the language you know is all here. What’s changed is everything around it. To follow along, install Node from nodejs.org, then check it from a terminal:
node --version
It prints the version you have, a v and three numbers.
The REPL
Type node with no file name, and you get a prompt. It reads a line, evaluates it, prints the result, and loops back for the next one. Read, eval, print, loop: a REPL. It’s the twin of the console in a browser’s developer tools.
Type these lines at the prompt in turn. The REPL shows the value of each line, with strings in single quotes:
typeof window // 'undefined'
typeof process // 'object'
path.join("data", "crew.json") // 'data/crew.json'
_ // 'data/crew.json'
There’s no window in Node, and there is a process, which the next section is about. The modules that come with Node are already loaded at the prompt, so path works without an import. An underscore holds the last result. And await works at the prompt too:
await Promise.resolve(80) // 80
A line that starts with a dot is a command for the REPL itself. .help lists them, and .exit brings the terminal back. The up arrow brings back the last line you typed. When you wonder what a line does, the prompt is the fastest way to find out.
The process
That object, process, stands where the page stood. In a browser, document is the page your script belongs to. In Node, process is the running program, so it knows how that program was started.
process.argv is an array of what was typed on the command line, which lets a script take input. Save this as greet.js, and run it with node greet.js Ada:
const name = process.argv[2];
console.log(`Welcome, ${name}!`); // Welcome, Ada!
Run node greet.js Lee, and the same file prints Welcome, Lee!. The name sits at index 2 because the first two entries are Node’s own path and the path to greet.js. Leave the name off, and it prints Welcome, undefined!.
process.env holds environment variables: settings kept outside the code, which is where a password or an API key belongs. You hand them to the program as you start it. Save this as port.js, and on a Mac or on Linux run PORT=8000 node port.js, which sets PORT for that one run:
console.log(process.env.PORT); // 8000
console.log(typeof process.env.PORT); // string
An environment variable is always text, so PORT arrives as the string '8000', and Number turns it into a number when you need one. A name that isn’t set gives undefined.
And when the last line has run and nothing is left waiting, the process ends by itself, and the terminal’s prompt comes back.
Reading and writing files
Now something no web page can do: read a file straight off the disk. The modules Node comes with are called core modules, and the one for files is fs, short for file system. Make a folder with a file in it called crew.json, holding two names:
["Ada","Lee"]
Then save this beside it as add.js, and run node add.js:
import { readFile, writeFile } from "node:fs/promises";
const text = await readFile("crew.json", "utf8");
const crew = JSON.parse(text);
crew.push("Omar");
await writeFile("crew.json", JSON.stringify(crew));
It prints nothing, and crew.json now reads ["Ada","Lee","Omar"].
You import from a core module the way you import from any module, with node: in front of its name to mark it as built in. A file that uses import is a module, so await can sit outside a function. readFile takes a path and returns a promise, so you await it. Ask for "utf8", and you get the whole file as one string. The string holds JSON, so JSON.parse turns it into an array. Leave "utf8" out, and you get the raw bytes instead, in a Buffer that prints them as numbers, one for each character here: <Buffer 5b 22 41 64 61 22 …>.
writeFile goes the other way. It takes a path and a string, and the file on disk is replaced. Nothing asks your permission first. A Node script can touch whatever you can, so run only code you trust.
Older code imports readFile from node:fs instead, and passes it a callback where this code awaits a promise. Same module, same work.
Paths
That script has a trap in it. A bare file name is looked up in the folder you ran the command from. Not the folder the script is in.
To see it, put add.js and crew.json in a folder called app, set crew.json back to ["Ada","Lee"], and run the script from the folder above:
node app/add.js
The file isn’t found, and nothing is written:
Error: ENOENT: no such file or directory, open 'crew.json'
The folder you ran the command from is process.cwd(). The fix has two parts. import.meta.dirname is the folder this file lives in, wherever the command ran. And the path module has join, which glues pieces of a path together with the right separator: a slash on a Mac or on Linux, a backslash on Windows. Join the script’s folder to the file’s name:
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const file = join(import.meta.dirname, "crew.json");
const text = await readFile(file, "utf8");
const crew = JSON.parse(text);
crew.push("Omar");
await writeFile(file, JSON.stringify(crew));
Now node app/add.js works from the folder above, and node add.js from inside app. Either way crew.json ends up with Omar in it. Older files, the ones that load modules with require, call this folder __dirname. In a module, __dirname isn’t defined.
The same module takes paths apart, too. basename gives a path’s file name, and extname its extension. At the prompt:
path.basename("/app/data/crew.json") // 'crew.json'
path.extname("kestrel.html") // '.html'
A server
Now the thing Node is known for. A server is a program that waits for requests and answers them, and you can write one in Node. The core module is http, and its function is createServer.
You hand createServer a function of your own, and Node calls it once for each request that arrives, with two objects. request is what came in: the method, the path, the headers. response is what goes back. Save this as server.js in the folder that holds crew.json:
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
const crewFile = join(import.meta.dirname, "crew.json");
const crew = JSON.parse(await readFile(crewFile, "utf8"));
const server = createServer((request, response) => {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(crew));
});
server.listen(8000);
writeHead sets the status and the headers, and end sends the body. Last, listen picks a port: 8000. Run node server.js, open http://localhost:8000 in a browser, and your function’s answer is the page: ["Ada","Lee","Omar"]. The terminal prints nothing, and its prompt doesn’t come back. Ctrl+C stops the server.
curl, a command-line tool that sends a request and prints the answer, shows the whole response:
curl -i http://localhost:8000
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 13 Nov 2026 13:56:13 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
["Ada","Lee","Omar"]
Your code set the status and Content-Type. Node added the four lines after them. Start a second copy while the first is running, and it stops at once with Error: listen EADDRINUSE: address already in use :::8000: only one program can listen on a port.
Method and path
That server gives every request the same answer, whatever it asks for. So the function’s first job is to see what was asked. Join the method to the path with a space, and you have the first part of the request’s first line, like GET /crew. Then add an if for each request the server knows.
The page this server sends is kestrel.html. Its script is inside the page, and it asks the server for /crew and makes a list item for each name:
<!DOCTYPE html>
<html>
<head>
<title>Kestrel</title>
</head>
<body>
<h1>Kestrel: on the pad</h1>
<button>Launch</button>
<progress id="fuel" value="80" max="100"></progress>
<ul></ul>
<script type="module">
const response = await fetch("/crew");
const crew = await response.json();
for (const name of crew) {
const item = document.createElement("li");
item.textContent = name;
document.querySelector("ul").append(item);
}
</script>
</body>
</html>
Save it beside server.js, and replace the server with this:
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
const crewFile = join(import.meta.dirname, "crew.json");
const pageFile = join(import.meta.dirname, "kestrel.html");
const crew = JSON.parse(await readFile(crewFile, "utf8"));
const server = createServer(async (request, response) => {
const route = `${request.method} ${request.url}`;
if (route === "GET /") {
response.writeHead(200, { "Content-Type": "text/html" });
response.end(await readFile(pageFile));
} else if (route === "GET /crew") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(crew));
} else {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("Not found");
}
});
server.listen(8000);
Stop the old server, start this one, and open http://localhost:8000 again. GET / reads the page’s file and sends it as HTML. The page’s script then sends GET /crew, gets the array as JSON, and the list fills in: Ada, Lee, Omar. The function is async now, because the first branch awaits the read.
Everything else falls through to the last else. Open http://localhost:8000/crews, and the answer is status 404, with a body that says Not found. That’s all a 404 ever was. Not the network failing. A branch in somebody’s server code, where they picked that number. Chrome finds this branch on its own, too: it asks for /favicon.ico, an icon for the tab, and the developer tools log a 404 for it. That line is about the icon.
Every file a page loads is one more request. A stylesheet or a separate script file would need a branch of its own, which is why this page keeps its script inside.
Why it keeps running
Look at the terminal while the server runs. Every script before this one ran its last line and ended. This one is still going, and the event loop explains it. It’s the same loop that runs a page. Each time the call stack empties, Node checks what’s still pending: a timer, a file being read, a port being listened on. Nothing pending? The program ends.
A timer is enough to keep a program alive for a while. Save this as wait.js and run it:
setTimeout(() => console.log("Three seconds later"), 3000);
console.log("Last line");
// Last line
// Three seconds later
The last line prints at once. The program waits for the timer, runs it, and only then ends. A server always has something pending: its port. So Node waits. A request arrives, your function rides the queue onto the call stack, runs, and leaves the stack empty again.
And there is only one stack. Your JavaScript runs on a single thread, so the server runs one request’s code at a time.
Non-blocking I/O
One at a time sounds slow. It isn’t, because of what happens when your code has to wait. Reading a disk or a network is called I/O, input and output, and next to running code it takes forever.
So when you await readFile, Node hands the read off, outside your JavaScript, and your function steps aside. The thread is free, and the next request’s code runs while the disk works. When the read is done, your function comes back through the queue. That’s non-blocking I/O. You can watch the order in a file of its own, order.js, beside crew.json:
import { readFile } from "node:fs/promises";
console.log("before");
readFile("crew.json", "utf8").then(() => console.log("file read"));
console.log("after");
// before
// after
// file read
after printed before file read. The thread didn’t wait for the disk.
That answers the question from the start. One thread keeps up with thousands of visitors because it never stands waiting. File reads run on a few threads inside Node, and waiting on the network is left to the operating system. Your JavaScript stays on its one thread, which moves on to the next piece of code.
Unless you make it wait. readFileSync, from node:fs, reads the same file and blocks: the thread sits on that line until the disk answers.
import { readFileSync } from "node:fs";
console.log("before");
const text = readFileSync("crew.json", "utf8");
console.log("file read");
console.log("after");
// before
// file read
// after
In a server, every other request waits behind that line. Measured on a laptop, with a 512 MB file in place of the page, a request for /crew sent just after a request for / waited about 60 ms behind readFileSync, and 2 ms behind await readFile. A long calculation blocks the same way, since it runs on the thread too. In a server, use the version you can await.
Streams
Look again at the branch that sends the page. readFile brings the whole file into memory before the first byte goes out. For a small page, that’s fine. For a two-gigabyte video, it’s two gigabytes held in memory for every visitor who asks.
So Node has streams: data handed over in chunks, not all at once. createReadStream opens a file as a stream you read from. process.stdout, the terminal’s output, is a stream you write to. And pipe connects the two, so each chunk goes out as soon as it’s read. Save this as show.js beside kestrel.html, and run it to see the page’s HTML in the terminal:
import { createReadStream } from "node:fs";
createReadStream("kestrel.html").pipe(process.stdout);
A file’s chunks are 64 KB each, so memory stays flat however big the file is. Measured on a laptop, a 512 MB file read whole took the program to 563 MB of memory. Streamed, it stayed under 90 MB.
The server’s response is a stream you write to as well. So the page’s branch takes two changes. Add import { createReadStream } from "node:fs"; at the top, and send the page with createReadStream(pageFile).pipe(response); in place of response.end(await readFile(pageFile));. Nothing in the function is awaited now, so the async goes too. The next section has the server with both changes.
pipe has one weakness. It reports nothing, so a missing file stops the program with an ENOENT error that nothing caught. pipeline, from node:stream/promises, connects the same two ends and returns a promise, which rejects if either end fails. Save this as copy.js beside kestrel.html:
import { createReadStream, createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
try {
await pipeline(createReadStream("kestrel.html"), createWriteStream("copy.html"));
console.log("Copied");
} catch (error) {
console.log(error.message);
}
// Copied
Change "kestrel.html" to a name that doesn’t exist, and the catch prints ENOENT: no such file or directory and the name.
Streams run all through Node: files, responses, and, as it turns out, requests.
Answering a POST
In the fetch lesson, the page sent the server a new name as JSON, in the body of a POST. Here’s the server that answers it. The request is a stream too, so its body arrives the way that file did: in chunks.
import { createServer } from "node:http";
import { createReadStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const crewFile = join(import.meta.dirname, "crew.json");
const pageFile = join(import.meta.dirname, "kestrel.html");
const crew = JSON.parse(await readFile(crewFile, "utf8"));
const server = createServer((request, response) => {
const route = `${request.method} ${request.url}`;
if (route === "GET /") {
response.writeHead(200, { "Content-Type": "text/html" });
createReadStream(pageFile).pipe(response);
} else if (route === "GET /crew") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(crew));
} else if (route === "POST /crew") {
let text = "";
request.on("data", (chunk) => {
text += chunk;
});
request.on("end", async () => {
const { name } = JSON.parse(text);
crew.push(name);
await writeFile(crewFile, JSON.stringify(crew));
response.writeHead(201, { "Content-Type": "application/json" });
response.end(JSON.stringify({ id: crew.length, name }));
});
} else {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("Not found");
}
});
server.listen(8000);
Each chunk is a data event. You listen with on, Node’s version of addEventListener, and add the chunk to a string. The end event says the body is complete. From there it’s familiar: JSON.parse turns the text into an object, the name goes into the array, and writeFile saves the array, so it survives a restart. Then the answer: status 201, for created, and a body with the name and its id.
To try it, restart the server, open http://localhost:8000, and paste this whole into the console of the browser’s developer tools. It’s the request from the fetch lesson:
const response = await fetch("/crew", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Zoe" }),
});
const saved = await response.json();
console.log(saved); // {id: 4, name: 'Zoe'}
Reload the page, and Zoe is fourth in the list. crew.json holds all four names now, so they’re still there after you stop the server and start it again.
A chunk is a Buffer, a run of bytes, and text += chunk turns each one into text on its own. That goes wrong when a character takes more than one byte and the chunks split it. Send Zoé with the é cut across two chunks, and the server saves Zo��. Call request.setEncoding("utf8") before adding the listeners, and the chunks arrive as strings with every character whole.
A login cookie
The storage lesson promised a server that answers POST /login with Set-Cookie: login=k7m2x9; HttpOnly. A cookie from the server is one more header on a response, so it’s one more branch. Add this above the last else:
} else if (route === "POST /login") {
response.writeHead(200, {
"Content-Type": "text/plain",
"Set-Cookie": "login=k7m2x9; HttpOnly",
});
response.end("Signed in");
Restart the server, and ask for it with curl:
curl -i -X POST http://localhost:8000/login
HTTP/1.1 200 OK
Content-Type: text/plain
Set-Cookie: login=k7m2x9; HttpOnly
Date: Fri, 13 Nov 2026 14:04:48 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
Signed in
Now from the page. Open http://localhost:8000, and type these lines in the console in turn:
const response = await fetch("/login", { method: "POST" });
await response.text(); // 'Signed in'
document.cookie; // ''
The browser stored the cookie, and document.cookie doesn’t list it, because it’s HttpOnly: no script on the page can read it. The browser still sends it. Reload the page, and in the Network panel, the requests for / and /crew both carry Cookie: login=k7m2x9 in their headers. The server can read it there, as request.headers.cookie.
This branch hands the same token to anyone who asks, which is only good for trying the cookie out. A real one reads a name and a password from the body, the way the POST /crew branch reads its name, checks them, and makes a new random token for each sign-in.
Packages and npm
All of that came with Node. The rest is everyone else’s code. A package is code that somebody published for others to use, and most live on npm, a registry with millions of them. npm is also the tool that fetches them, and it comes with Node. In the server’s folder, type npm install and a name. This one is chalk, which colors text in a terminal:
npm install chalk
npm prints added 1 package and how long it took. A folder called node_modules appears, with the package inside it. Now an import with a bare name works, because Node looks a bare name up in that folder.
Make import chalk from "chalk"; the first line of server.js. And change the last line to server.listen(8000, () => console.log(chalk.green("Listening on port 8000")));, which prints a green line once the server is listening. Before the install, that import fails with Cannot find package 'chalk'. The install also wrote package.json, a record of what you installed:
{
"dependencies": {
"chalk": "^6.0.1"
}
}
^6.0.1 accepts any later version 6, and never a 7. Beside it, package-lock.json pins the exact version of everything installed. Because of that record, the node_modules folder itself is never shared. Run npm install with no name, and npm rebuilds it from the list.
Run the server now, and Node prints a warning before it starts: Module type of file://…/server.js is not specified. Add one line to package.json, and Node knows your files use import:
{
"type": "module",
"dependencies": {
"chalk": "^6.0.1"
}
}
One caution. A package is a stranger’s code, running with your permissions. Install what’s widely used.
Both ends of the wire
Now put both halves side by side. On one end, a page: JavaScript in a browser, with a document and no way to reach a file. On the other, a server: JavaScript in Node, with files and no document at all. That’s why typeof window gave 'undefined' at the prompt. Nothing was missing. The page was on the other end of the wire.
Between the two travels text. The page calls JSON.stringify on what it sends, and the server calls JSON.parse on what arrives. The server’s answer goes back the same way.
On a real project, a package such as Express writes the routing for you (npm install express), and a database takes the place of crew.json. Underneath, it’s still this: one function, one request, one response. And restarting the server by hand after each change gets old: node --watch server.js restarts it whenever you save the file.
The whole server
Here is everything this lesson built into server.js: the page, the crew, the POST that adds a name, the login cookie, and chalk’s green line. Save it beside kestrel.html and crew.json, in a folder where you’ve run npm install chalk and added "type": "module" to package.json, then start it with node server.js:
import chalk from "chalk";
import { createServer } from "node:http";
import { createReadStream } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const crewFile = join(import.meta.dirname, "crew.json");
const pageFile = join(import.meta.dirname, "kestrel.html");
const crew = JSON.parse(await readFile(crewFile, "utf8"));
const server = createServer((request, response) => {
const route = `${request.method} ${request.url}`;
if (route === "GET /") {
response.writeHead(200, { "Content-Type": "text/html" });
createReadStream(pageFile).pipe(response);
} else if (route === "GET /crew") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify(crew));
} else if (route === "POST /crew") {
let text = "";
request.on("data", (chunk) => {
text += chunk;
});
request.on("end", async () => {
const { name } = JSON.parse(text);
crew.push(name);
await writeFile(crewFile, JSON.stringify(crew));
response.writeHead(201, { "Content-Type": "application/json" });
response.end(JSON.stringify({ id: crew.length, name }));
});
} else if (route === "POST /login") {
response.writeHead(200, {
"Content-Type": "text/plain",
"Set-Cookie": "login=k7m2x9; HttpOnly",
});
response.end("Signed in");
} else {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("Not found");
}
});
server.listen(8000, () => console.log(chalk.green("Listening on port 8000")));
// Listening on port 8000
Summary
- Node is a runtime: the V8 engine from Chrome, handed your computer in place of a page. The language is the same, and
console, timers andfetchcome from the runtime. nodewith no file name opens the REPL, a prompt that reads, evaluates and prints a line at a time.processis the running program.process.argvholds the command line, andprocess.envholds environment variables, as strings.readFileandwriteFilefromnode:fs/promisesread and write a whole file. A bare file name starts from the folder the command ran in, so joinimport.meta.dirnameto it withjoinfromnode:path.createServerfromnode:httpcalls your function once for each request. Branch on the request’s method and path, and answer withwriteHeadandend.- A server keeps running because the event loop has a port to listen on. Your JavaScript runs on one thread, which non-blocking I/O keeps free while a disk or the network works.
readFileSyncblocks it. - Streams move data in chunks:
createReadStream(...).pipe(response)sends a file of any size with little memory, and a request’s body arrives asdataevents and anend. - A response sets a cookie with a
Set-Cookieheader.HttpOnlykeeps it out ofdocument.cookie, and the browser still sends it back. - npm installs packages into
node_modulesand records them inpackage.json, where"type": "module"says your files useimport.
Next in this series: the tools around the language. npm scripts that run a project’s commands, a bundler that packs modules for the browser, TypeScript, which checks types before the code runs, and tests.
Video transcript
Intro
This is a web server, written in JavaScript and running on Node. Ten thousand visitors just asked it for a page, all at the same moment, and every one of them got an answer. Yet Node runs your JavaScript on a single thread, which means one piece of code at a time. So how does one thread keep up with ten thousand visitors? Today, we find out.
By the end of this video, you'll understand three things. One: what Node is: the engine that runs JavaScript in Chrome, with your computer around it in place of a page. Two: its core modules: fs for files, path, streams, and http, which turns one function into a server. Three: how that server handles many requests on a single thread: the event loop, plus non-blocking I/O.
What Node is
Inside Chrome there's an engine called V8. It's the part that reads JavaScript and runs it: values, functions, classes, promises. That is the language, and V8 knows nothing beyond it: it has never seen a page or a network, and it can't even set a timer. Everything else is handed in by the program the engine sits inside, which is called a runtime. Chrome is one runtime. It hands the engine a page: document, window, buttons, storage. Node is another, built around the same engine. It hands over the computer: its files, its network, the running program itself. A few things both supply, each in its own way: the console, timers, fetch. So the language you've learned is all here. What's changed is everything around it.
The REPL
First, a place to try things. Type node with no file name, and you get a prompt. It reads a line, evaluates it, prints the result, and loops back for the next one. Read, eval, print, loop: a REPL. It's the browser console's twin. Ask it for the type of window: undefined. Ask for process: an object. The modules that come with Node are already loaded here, so you can call one without importing it. An underscore holds the last result. And dot exit brings the terminal back. When you wonder what a line does, this is the fastest way to find out.
The process
That object, process, stands where the page stood. In a browser, document is the page your script belongs to, and in Node, process is the running program it belongs to, so it knows how that program was started. process dot argv is an array of what was typed on the command line, which lets a script take input: run the same file with a different name after it, and it prints a different line. process dot env holds environment variables, settings kept outside the code, which is where a password or an API key belongs. And when the last line has run and nothing is left waiting, the process ends by itself.
Reading and writing files
Now something no web page can do: read a file straight off the disk. The modules Node comes with are called core modules, and the one for files is fs, short for file system. You import from it like any other module, with the word node and a colon in front, which marks it as built in. readFile takes a path and returns a promise, so you await it. Ask for text, and you get the whole file as one string. This file holds JSON, so JSON dot parse turns it into an array. writeFile goes the other way: a path and a string, and the file on disk is replaced. Nothing asks your permission first. A Node script can touch whatever you can, so run only code you trust.
Paths
That script has a trap in it. A bare file name is looked up in the folder you ran the command from. Not the folder the script is in. Run it from one folder up, and the file isn't found. The fix has two parts. import dot meta dot dirname is the folder this file lives in. And the path module has join, which glues pieces of a path together with the right separator: a slash on a Mac or on Linux, a backslash on Windows. Join the script's folder to the file's name, and the script works from anywhere. The same module takes paths apart, too: basename gives the file's name, and extname its extension.
A server
Now the thing Node is known for. Earlier in this series, a page sent requests to a server. A server is a program that waits for requests and answers them, and you can write one in Node. The core module is http, and its function is createServer. You hand it a function of your own, and Node calls that function once for each request that arrives, with two objects. request is what came in: the method, the path, the headers. response is what goes back: writeHead sets the status and the headers, and end sends the body. Last, listen picks a port: eight thousand. Run the file, open localhost, port eight thousand, in a browser, and your function's answer is the page.
Method and path
That function gets every request, whatever it's for. So its first job is to see what was asked. Join the method to the path with a space, and you have the first line of the request itself: GET slash crew. Then an if for each request the server knows. GET slash: read the page's file and send it as HTML. GET slash crew: send the array as JSON. And for everything else, a last else: status four-oh-four, and a body that says not found. That's all a four-oh-four ever was. Not the network failing. A branch in somebody's server code, where they picked that number.
Why it keeps running
Look at the terminal. The prompt hasn't come back. Every script before this ran its last line and ended. This one is still going. Why? The event loop: the one that runs a page runs here too. Each time the call stack empties, Node checks what's still pending: a timer, a file being read, a port being listened on. Nothing pending? The program ends. A server always has something: its port. So Node waits. A request arrives, your function rides the queue onto the stack, runs, and leaves the stack empty again. And there is only one stack. Your JavaScript runs on a single thread, so it handles one request's code at a time.
Non-blocking I/O
One at a time sounds slow. It isn't, because of what happens when your code has to wait. Reading a disk or a network is called I/O, input and output, and next to code it takes forever. So when you await readFile, Node hands the read off, outside your JavaScript, and your function steps aside. The thread is free, and the next request's code runs while the disk works. When the read is done, your function comes back through the queue. That's called non-blocking I/O. It answers the question we started with: one thread keeps up with thousands of visitors because it never stands waiting. Unless you make it. readFileSync blocks. The thread sits on that line until the disk answers, and every other request waits behind it. In a server, use the version you can await.
Streams
Look again at the branch that sends the page. readFile brings the whole file into memory before the first byte goes out. For a small page, that's fine. For a two-gigabyte video, it's two gigabytes held in memory for every visitor who asks. So Node has streams: data handed over in chunks, not all at once. createReadStream opens the file as a stream you read from. The response is a stream you write to. And pipe connects the two, so each chunk is sent as soon as it's read, and memory stays flat however big the file is. Streams run all through Node: files, responses, and, as it turns out, requests.
Answering a POST
One request is left: the POST that sends a new name, as JSON, in its body. The request is a stream too, so its body arrives the way that file did: in chunks. Each chunk is a data event. You listen with on, Node's version of addEventListener, and add the chunk to a string. The end event says the body is complete. From there it's familiar: JSON dot parse turns the text into an object, the name goes into the array, and writeFile saves the array, so it survives a restart. Then the answer: status two-oh-one, for created, and a body holding the name and its id. Exactly what the page was waiting for.
Packages and npm
All of that came with Node. The rest is everyone else's code. A package is code that somebody published for others to use, and most live on npm, a registry with millions of them. npm is also the tool that fetches them, and it's installed with Node. Type npm install and a name. This one is chalk, which colors text in a terminal. A folder called node modules appears, with the package inside it, and now an import with a bare name works: Node looks a bare name up in that folder. A file called package dot json records what you installed, so the folder itself is never shared. Run npm install with no name, and npm rebuilds it from the list. Add one line to that file, type, module, and Node knows your files use import. One caution. A package is a stranger's code, running with your permissions. Install what's widely used.
Both ends of the wire
Now put both halves side by side. On one end, a page: JavaScript in a browser, with a document and no way to reach a file. On the other, a server: JavaScript in Node, with files and no document at all. That's why the type of window was undefined at the prompt. Nothing was missing. The page was on the other end of the wire. Between the two travels text: stringify on one side, parse on the other. On a real project, a package such as Express writes the routing for you, and a database takes the file's place. Underneath, it's still this: one function, one request, one response.
In one line
That's Node in one line: the JavaScript engine from Chrome, handed a computer in place of a page; fs reads and writes files, path builds their addresses, and streams move them a chunk at a time; http turns one function into a server; non-blocking I/O, under the event loop, lets a single thread run it; and npm brings in everyone else's code.
Next time
Next time, we pick up the tools around the language: npm scripts that run a project's commands, a bundler that packs modules for the browser, TypeScript, which checks types before the code runs, and tests.

