How Node really works · Chapter 2 of 34
Globals
By the end of this chapter you can use the tools Node puts in every file without an import: deep copies, URLs, bytes, fetch, microtasks and the module's own folder. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: How Node runs
- 6 tasks
- Node.js
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Anjali needs tracking links for the delivery SMS, receipt lines for the kitchen printer, and the menu from the new menu service. Ravi wants the kitchen display to redraw once per burst of orders, not once per order, and a script that crashes on the server fixed.
Hand-made versions of each go wrong quietly. A copy made through JSON loses its dates, a link glued from strings breaks on an &, a string's length is not its size in bytes, and a fetch that got a 503 still "works". Node has a global for each of these, and one global that old code expects is missing.
The lesson
A real deep copy
The old trick, a JSON round trip, keeps only what JSON can write down. structuredClone copies Dates, Maps, Sets and nested objects as the real thing:
const rider = {
name: 'Imran',
joinedAt: new Date('2025-11-03T09:00:00Z'),
zones: new Set(['Indiranagar', 'Domlur']),
};
const viaJson = JSON.parse(JSON.stringify(rider));
console.log(viaJson.joinedAt, typeof viaJson.joinedAt);
console.log(viaJson.zones);
const copy = structuredClone(rider);
copy.zones.add('HAL');
console.log(copy.joinedAt instanceof Date, copy.zones.size, rider.zones.size);
2025-11-03T09:00:00.000Z string
{}
true 3 2
The JSON copy turned the date into a string and the set into an empty object. The clone kept both, and adding a zone to it left the original alone. A spread ({ ...rider }) would not help: it is a new object, but the Set inside is the same one. What structuredClone cannot copy, it refuses, such as a function:
DOMException [DataCloneError]: () => 'ring ring' could not be cloned.
URLs, encoded for you
Gluing a value into a link breaks on the first &:
const glued = 'https://tapri.app/search?q=' + 'bun & chai';
console.log([...new URL(glued).searchParams]);
const url = new URL('/search', 'https://tapri.app');
url.searchParams.set('q', 'bun & chai');
url.searchParams.set('page', 2);
console.log(url.href);
console.log([...url.searchParams]);
[ [ 'q', 'bun ' ], [ ' chai', '' ] ]
https://tapri.app/search?q=bun+%26+chai&page=2
[ [ 'q', 'bun & chai' ], [ 'page', '2' ] ]
new URL(path, base) joins a path onto a base, and searchParams.set encodes each value (a space becomes +, & becomes %26) and turns a number into a string. A path with no base is not a URL: new URL('/search') throws TypeError: Invalid URL.
Bytes are not characters
A printer or a socket counts bytes, and in UTF-8 one character can take up to four. Buffer holds raw bytes, and can also write a number into them, biggest byte first (BE) or last (LE):
fetch resolves on a 404
fetch is the browser's HTTP client, built in. It resolves as soon as the server answers, whatever the answer:
import { createServer } from 'node:http';
const server = createServer((req, res) => {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'no such rider' }));
});
server.listen(0, async () => {
const { port } = server.address();
const res = await fetch(`http://127.0.0.1:${port}/riders/99`);
console.log(res.status, res.ok);
console.log(await res.json());
server.close();
});
404 false
{ error: 'no such rider' }
Only a network failure rejects, here a port where nothing listens: TypeError fetch failed, with ECONNREFUSED in err.cause.code. So look at res.ok (true for 200 to 299) before you trust the body.
queueMicrotask: right after this code
queueMicrotask(fn) runs fn once the running code has finished, before any timer:
setTimeout(() => console.log('timer'), 0);
queueMicrotask(() => console.log('microtask'));
console.log('sync');
sync
microtask
timer
That makes it the place to collect a burst and deal with it once. A logger that queues one microtask per line still writes once per line:
No __dirname in an ES module
CommonJS files get __dirname and __filename. Every .js file here is an ES module, and there they do not exist:
ReferenceError: __dirname is not defined in ES module scope
Each module has import.meta instead. Run from /tmp, a file in the demo folder prints:
console.log(import.meta.url);
console.log(import.meta.filename);
console.log(import.meta.dirname);
console.log(process.cwd());
file:///workspace/chapters/demo/meta.js
/workspace/chapters/demo/meta.js
/workspace/chapters/demo
/tmp
process.cwd() is where the command was started, not where the file lives.
Your turn
Your six tasks are at the top, all in exercise.js. The traps: the copy must keep real Dates and Maps, an error status must throw with the status code in the message, and every batch must be a new array. For Dev's interview question, fix dataFile so it works from any folder, and be ready to say why the old line crashes.
What you build: 6 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
copyOrder: copy an order deeply, dates and extras included
Write copyOrder(order). It returns a deep copy: a new object equal to the order, where changing the copy's items, its placedAt Date or its extras Map never changes the original.
In the copy, placedAt is still a real Date with the same time, and extras is still a real Map with the same entries.
- Task 2
trackingUrl: a tracking link that survives spaces and ampersands
Write trackingUrl(base, params). It returns the full link (a string) to the /track path on base, with every entry of params as a query parameter, in the order given, and every value encoded: a space becomes + and & becomes %26. Values may be numbers.
base may end with a slash or not. With an empty params the link has no question mark at all, like http://localhost:3000/track.
- Task 3
printerFrame: a receipt line for the kitchen printer, in bytes
Write printerFrame(text). It returns a Buffer: two bytes holding the number of bytes the text takes in UTF-8, as an unsigned 16-bit big-endian number, followed by those UTF-8 bytes.
Count bytes, not characters: 'Chai ₹40' is 8 characters but 10 bytes, so its frame is 12 bytes long and starts with 00 0a.
- Task 4
fetchMenu: fetch the menu, and refuse bad answers
Write fetchMenu(url), an async function. It fetches url with the global fetch, reads the body as JSON and resolves to its items array; the body's other fields, such as updatedAt, are left out.
When the server answers with an error status (a response that is not ok, such as 503), it rejects with an Error whose message contains the status code, for example Menu request failed: 503.
- Task 5
makeBatcher: one batch per burst of orders
Write makeBatcher(flush). It returns a function add(item). Every item added during one run of synchronous code is passed to flush as one array, in the order added, exactly once, in a microtask right after that code finishes: flush is not called while add is being called, and it runs before any timer.
Items added later form a new batch, in a new array. A batch already passed to flush must never change afterwards.
- Task 6 · interview question
Interview: fix dataFile, which crashes with __dirname is not defined
dataFile(name) must return the absolute path of name in the folder where exercise.js itself lives, for example /workspace/chapters/02-globals/menu.json, whatever folder the script is started from.
Today it crashes in plain Node with ReferenceError: __dirname is not defined in ES module scope. The check runs it in plain Node, started from another folder.
What you will learn
- structuredClone and URL: a real deep copy, and addresses encoded properly.
- Buffer: the bytes of a string, and numbers written into bytes.
- fetch and queueMicrotask: a request that can fail without rejecting, and work that waits for the running code to finish.
- import.meta: where this module's file lives, now that __dirname is gone.
More in How Node runs
Build "Globals" yourself
Tapri’s order server must never stall at the 4 pm rush. You learn why it would. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.