What Node.js Is: A Runtime, a Single Thread and an Event Loop
Run JavaScript outside the browser with Node.js, read the command line, environment and exit codes, and understand the single-threaded event loop by seeing a blocked loop delay a timer, with results checked from the shell.
In this lesson you will
- Explain what Node.js is
- Run scripts and read arguments and environment
- Use exit codes
- See how blocking code delays the event loop
About 28 minutes
Mara’s print shop needs a tool
Mara runs a small print shop that sells posters, flyers and business cards. Orders arrive in a spreadsheet export, and she spends an hour every morning adding them up, checking for mistakes and writing the day’s job list. She knows a little JavaScript from a website course, and wants a tool that does the morning work in a second. Node.js lets her use the language she already knows outside the browser. It is a runtime: a program that takes JavaScript, built on the V8 engine that Chrome uses, and adds what a browser does not give: access to files, the network, the operating system and other programs. With it, JavaScript can write command-line tools, web servers and automation scripts.
Two ideas explain how Node works. First, your JavaScript runs on a single thread, one line at a time, so there are no two pieces of your code running at the same instant, which removes a whole class of bugs. Second, anything slow that is not your own computation, such as reading a file, waiting for a network reply or a timer, is handed to the operating system, and your code gets a callback when it finishes. The event loop is the mechanism that waits for those results and runs the callbacks, one after another. Node is therefore excellent for programs that spend most of their time waiting for input and output, such as servers, and poor for long calculations on the main thread, because a calculation blocks the loop and nothing else can run until it ends.
| Browser JavaScript | Node.js JavaScript |
|---|---|
| document, window, DOM | process, fs, http, path |
| Runs in a tab, sandboxed | Runs as a program, with full access |
| Loaded by HTML script tag | Run with node script.js |
| One page at a time | Whatever you build: tools, servers |
const args = process.argv.slice(2);
console.log('arguments:', args);
const get = name => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
console.log('--name =', get('--name'), '| --copies =', Number(get('--copies')) * 2, '(doubled)');
console.log('NODE_ENV is', process.env.NODE_ENV === undefined ? 'not set' : process.env.NODE_ENV);
console.log('major version:', Number(process.versions.node.split('.')[0]), '| is a number:', typeof process.pid === 'number');
const { spawnSync } = require('child_process');
const exit3 = spawnSync(process.execPath, ['-e', 'process.exit(3)']);
const boom = spawnSync(process.execPath, ['-e', 'throw new Error("boom")']);
console.log('child that calls process.exit(3) ->', exit3.status, '| child that throws ->', boom.status, '| error text mentions boom:', boom.stderr.toString().includes('boom'));
let ticks = 0;
const timer = setInterval(() => ticks++, 10);
function busy(ms) { const end = Date.now() + ms; while (Date.now() < end) {} }
setTimeout(() => {
const before = ticks;
busy(300);
const during = ticks - before;
console.log('timer ticks while the loop was blocked for 300 ms:', during);
setTimeout(() => {
console.log('timer ticks in the next 300 ms of a free loop:', ticks - before >= 15 ? 'about 30 (>= 15)' : 'too few');
clearInterval(timer);
console.log('DATA ' + JSON.stringify({ args, during, free: ticks - before, status3: exit3.status, statusBoom: boom.status }));
}, 300);
}, 50);
arguments: [ '--name', 'Mara', '--copies', '50' ]
--name = Mara | --copies = 100 (doubled)
NODE_ENV is not set
major version: 22 | is a number: true
child that calls process.exit(3) -> 3 | child that throws -> 1 | error text mentions boom: true
timer ticks while the loop was blocked for 300 ms: 0
timer ticks in the next 300 ms of a free loop: about 30 (>= 15)
The first lines show the command line. The script was started with the arguments –name Mara –copies 50, which Node puts in process.argv after the path of Node itself and of the script, so slice(2) gives [‘–name’, ‘Mara’, ‘–copies’, ’50’]. A tiny helper reads a value that follows a flag, and the number of copies was converted with Number, since all arguments arrive as text. The environment variable NODE_ENV is not set by default, which is the usual signal for “not production” in many tools. The process knows its own major version, 22, and its id.
Exit codes are how programs tell their caller whether they succeeded. By convention 0 means success and anything else means failure. A child process that called process.exit(3) reported 3, and one that threw an uncaught error reported 1 and printed the error on its standard error stream. Shell scripts, schedulers and build systems test these codes, so a tool that Mara runs every morning should exit with 0 only when it really worked.
The last experiment shows the single thread. A timer was set to tick every 10 milliseconds. The script then ran a busy loop for 300 milliseconds, doing nothing but checking the clock, and the timer ticked 0 times during it: the timer could not fire, because the one thread was busy. In the next 300 milliseconds, with a free loop, it ticked 30 times, close to the expected 30. This is the difference between waiting, which is cheap, and computing, which blocks. A web server that does a long calculation inside a request handler cannot answer anyone else until it is finished, which is why heavy work belongs in worker threads or other processes, as lesson 11 shows.
Independent check from the shell: the command node –version prints v22.23.5, whose major number agrees with process.versions in the script. The command node -p “6*7” printed 42, and a shell that ran node -e “process.exit(3)” and then echoed its own status variable printed 3, the same code that the script observed from its child. So the claims about versions and exit codes do not depend on the script that made them.
Check by hand: with a 10 millisecond interval, a free loop of 300 milliseconds fits about 30 ticks. A blocked loop gets none, because JavaScript callbacks run only between pieces of your own code, never in the middle of one. The first timeout waits 50 milliseconds before blocking so the interval has started.
A long loop, a synchronous file read of a large file or a heavy calculation in a request handler freezes every other request. Use asynchronous functions, streams or worker threads.
Node.js has a yearly release cycle, and even-numbered versions become long-term support releases. Use one for anything you keep running, and read the release schedule on nodejs.org.
Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation.
Practice
Write a script that prints the first argument in capital letters, and exits with 2 if no argument is given. Run it from a shell and print the exit code with the status variable. Change the busy loop to 100 milliseconds and predict the number of ticks.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is Node.js?
- A browser
- A runtime that runs JavaScript outside the browser
- A database
- A CSS tool
Built on the V8 engine.
What does process.argv.slice(2) give?
- The command-line arguments of the script
- The environment
- The version
- The exit code
The first two entries are node and the script path.
What does exit code 0 mean?
- Success
- Failure
- Timeout
- Warning
Any other number means failure.
Why did the timer not tick during the busy loop?
- Timers are broken
- The loop was async
- Node paused
- JavaScript runs on one thread and the loop was blocked
Callbacks run between pieces of code.
What is Node.js good at?
- Long CPU-bound loops on the main thread
- Drawing
- Printing
- Programs that wait for input and output
Servers, tools, automation.
Summary
- Node.js runs JavaScript outside the browser and adds files, network and processes.
- Your code runs on one thread; I/O is handled by the event loop.
- Exit codes tell callers whether a program succeeded.
- Blocking code freezes everything else.
Questions
Do I need to know the browser JavaScript first?
The language is the same, so what you know carries over, and the objects differ: there is no document or window in Node. If you know no JavaScript, learn the basics first.
Is Node.js only for web servers?
No. It is also used for command-line tools, build tools, scripts, desktop apps and automation.
How do I install Node.js?
Download it from nodejs.org or use a version manager. Check the site for current instructions and the current long-term support release.
