Course outline · 0% complete

0/29 lessons0%

Course overview →

Node.js: JavaScript Outside the Browser

lesson 1-2 · ~9 min · 2/29

What Node.js actually is

JavaScript was born inside browsers. For years it could only run there, wired to web pages.

Node.js (2009) took the JavaScript engine out of Chrome (called V8) and wrapped it in a standalone program. Now JavaScript runs anywhere: your laptop, a server in a data center, a Raspberry Pi.

What changes outside the browser?

In the browserIn Node.js
document, window, DOMnot available, there is no page
cannot touch your filesfull file system access (fs)
cannot open a portcan be a server (http)
runs when a page loadsruns when you type node app.js

Two of those rows lean on a new word. A port is a number (0 to 65535) that your operating system uses to deliver incoming network traffic to the right program: when a program claims port 3000, every connection addressed to that number on your machine is handed to that program. A server must claim a port to receive requests at all, which is why “cannot open a port” is the biggest thing browser JavaScript cannot do and Node can.

The language is the same one you learned in Advanced JavaScript: functions, objects, callbacks, promises. Only the surroundings change.

Quiz

Your laptop runs a Node API and a database at the same time, and network data arrives for both. How does the operating system know which program receives which data?

Callbacks still rule here

In Advanced JavaScript you learned callbacks: functions passed to other functions to run later. Node is built on them, because a server spends most of its life waiting: for a database, a file, another API.

Node never sits idle during a wait. It starts the slow thing, hands over a callback, and moves on to the next request. When the slow thing finishes, the callback runs. This is called being non-blocking.

The example below fakes a slow operation with setTimeout. Watch the order of the printed lines: the program does not stop at step 2 to wait.

Code exercise · javascript

Run this and read the output order carefully. Line 3 is scheduled first but prints last, because Node keeps going instead of waiting.

Quiz

Why is non-blocking behavior so important for a backend?

Code exercise · javascript

Your turn. Write a function loadConfig(callback) that uses setTimeout with a 10 ms delay to call callback({ port: 3000 }). Then call loadConfig and print "Server will use port " plus the port. Print "loading config..." immediately after calling loadConfig, before the callback fires.