../courses.php
Node
NODE102
90
JavaScript Escapes The Browser
Learn the difference between browser JavaScript and Node JavaScript.
What changes when JavaScript runs in Node instead of the browser?
Browser JavaScript works with the page. Node JavaScript works with the computer or server. Node can read files, create servers, use packages, run scripts, and respond to network requests.
JavaScript is the language, but the runtime decides what JavaScript can touch.
In the browser, JavaScript can work with the DOM, buttons, forms, windows, tabs, and page events.
In Node, JavaScript can work with files, paths, processes, packages, HTTP servers, and environment variables.
That means some code only belongs in the browser and some code only belongs in Node.
This is the first major Node habit: always know which runtime you are writing for.
Browser JavaScript versus Node JavaScript
// Browser JavaScript
const heading = document.querySelector("h1");
heading.textContent = "Changed by browser JavaScript";
// Node JavaScript
const fs = require("node:fs");
fs.writeFileSync(
"message.txt",
"Created by Node JavaScript"
);
console.log("File written.");
document.querySelector() belongs to browser page JavaScript.
Plain Node does not have the browser document object.
require("node:fs") loads Node's file system module.
writeFileSync() writes text into a file.
Node JavaScript can do server-side and computer-side work that browser JavaScript cannot safely do.
Runtime awareness
You must know whether code runs in the browser or in Node.
File access
Node can read and write files using built-in modules.
Server work
Node can listen for HTTP requests and create responses.
Security boundary
Browsers do not allow normal web pages to freely access your computer's files.
Wrong runtime
// This fails in plain Node.
document.querySelector("#app");
Node runtime code
const fs = require("node:fs");
fs.writeFileSync("message.txt", "Hello from Node");
Ask ChatGPT: "Which lines are browser-only and which lines are Node-only?" Then separate the code by runtime.
Write one browser-only JavaScript example.
Write one Node-only JavaScript example.
Use node:fs to create a text file.
Run the Node script from the terminal.
Explain why the browser example and Node example cannot be swapped directly.
Using browser globals in Node scripts.
Using Node file-system code inside front-end browser code.
Forgetting that the runtime provides different built-in tools.
Confusing JavaScript language syntax with runtime APIs.
Assuming server code is visible to the browser the same way front-end code is.
Explain how JavaScript changes when it runs in Node instead of the browser, and identify browser-only versus Node-only code.
Login - Jit4All
Login
Welcome back to Jit4All