Node.js Tutorial for JavaScript Developers, Step by Step
Node.js is a JavaScript runtime environment built on Chrome’s V8 engine. It runs JavaScript outside the browser, on your computer or a server. If you already know browser JavaScript, start by installing an LTS (Long Term Support) release. Then save a file with a .js extension and run it with node file.js in a terminal. This tutorial walks you through that path in numbered steps, each with code and the output to expect. How Node.js works in one minute Node.js is open-source and cross-platform, so it runs on Windows, macOS and Linux. It is not a programming language or a web server. It is a runtime environment: a program that executes JavaScript code for you. That is why it is used for server-side work, meaning code that runs on a server instead of in the visitor’s web browser (the client side). Your script goes to the node program, which uses V8 to compile and execute it. Instead of a page, a DOM and a window, you get access to the operating system through built-in modules. Examples are fs (files), http (network) and path (file paths). Node runs your code on a single main thread and hands slow work such as disk and network access to the system. This makes it non-blocking (it does not wait idle for slow tasks) and event-driven (it reacts when a task finishes). Step 6 explains this in detail. Typical uses include web applications, REST APIs (services that exchange JSON data over HTTP), command-line tools, real-time apps such as chat, and scripts that work with files. Step 1: Install an LTS release Go to nodejs.org and download the version labelled LTS. LTS releases receive fixes for a long period, so they suit learning and production. The “Current” release is meant for trying new features. The installer works on Windows, macOS and Linux, and a version manager such as nvm is a good option if you need several versions side by side. Open a terminal (Command Prompt, PowerShell or a Unix shell) and check the installation: node –version npm –version Expected output: two version numbers. They will match the release you installed. If you see “command not found”, close and reopen the terminal so the PATH (the list of folders where the system looks for programs) is refreshed. Step 2: Run your first script Create a folder, then a file named hello.js. This is the classic Hello World program: console.log(‘Hello from Node.js’); console.log(2 + 3); Run it with the following command: node hello.js Expected output: Hello from Node.js 5 You can also type node alone to open the REPL (read-eval-print loop), an interactive prompt where each line is evaluated immediately. Press Ctrl+C twice to leave it. Step 3: Understand how Node differs from the browser The language is the same, but the environment is not. This table shows what changes for a developer coming from the front end. Topic Browser Node.js Global object window globalThis (no window) DOM and document Available Not available Files and OS Blocked by the sandbox Available through fs, os, path Modules ES modules ES modules and CommonJS Main purpose Interfaces for users Servers, tools, scripts The DOM (Document Object Model) is the browser’s tree representation of an HTML page. Node has no page, so calls like document.querySelector() or alert() cause errors. To see the difference yourself, run this: console.log(typeof window); console.log(typeof process); console.log(process.platform); Expected output on Linux: undefined, object, linux. The process object describes the running program. It is specific to Node. Step 4: Use ES modules and npm Create a project npm (Node Package Manager) is installed with Node. It downloads libraries and records them in a package.json file, which describes your project and its dependencies. npm init -y Open the generated package.json and add “type”: “module”. This tells Node to treat .js files as ES modules, so you can use import and export as in the browser. Write and import a module A module is a file with reusable code that other files can import. Create math.js: export function add(a, b) { return a + b; } Create app.js: import { add } from ‘./math.js’; import os from ‘node:os’; console.log(add(2, 3)); console.log(os.platform()); Run node app.js. Expected output: 5 then your platform name, such as linux, darwin or win32. The node: prefix marks a built-in module and avoids confusion with npm packages. The older CommonJS style (require and module.exports) still exists, and you will meet it in many existing projects. Install a package npm install dayjs This creates a node_modules folder and adds the package to dependencies in package.json. Do not commit node_modules to Git. Anyone can rebuild it with npm install. Step 5: Work with files and async/await Reading a file takes time, so Node offers an asynchronous, promise-based API in node:fs/promises. Asynchronous means the program starts the task and continues, then gets the result later. Create notes.txt containing Learning Node, then files.js: import { readFile, writeFile } from ‘node:fs/promises’; const text = await readFile(‘notes.txt’, ‘utf8’); console.log(‘Read:’, text); await writeFile(‘copy.txt’, text.toUpperCase()); console.log(‘Copy written’); Expected output: Read: Learning Node Copy written Top-level await works here because the file is an ES module. In a CommonJS file you would wrap the code in an async function. Other useful functions from the same module are mkdir, readdir, rename and unlink (delete). Synchronous versions such as readFileSync exist, but they are blocking: they stop the whole process until they finish. Keep them for start-up scripts. Step 6: Understand the event loop Node has one main thread that runs your JavaScript. When you start a slow operation, Node delegates it and keeps going. When the operation finishes, its callback (the function you passed to be called afterwards) is queued. The event loop runs it once the current code is done. Try this: console.log(‘1: start’); setTimeout(() => console.log(‘3: timer’), 0); Promise.resolve().then(() => console.log(‘2: promise’)); console.log(‘1b: end of script’); Expected output: 1: start 1b: end of script 2: promise 3: timer Synchronous code runs first, then promise callbacks (the microtask queue), then timers. The practical consequence
Node.js Tutorial for JavaScript Developers, Step by Step Read More »
