Node.js Tutorial with Runnable Examples
A free Node.js tutorial with examples you run on the page: files, modules, the event loop, Express servers you send requests to, MongoDB and JWT. Edit the code and run it again.
Start the courseGetting Started
- What Is Node.jsNode.js is a runtime that runs JavaScript outside the browser, on servers and in the terminal. It is not a language and not a framework: it is V8 plus an event loop plus APIs for files, networks and processes.
- Node.js vs JavaScriptJavaScript is the language; Node.js is a program that runs it outside the browser. The syntax is identical, but the globals and built-in APIs around your code are different.
- process.argvprocess.argv is an array of the command line that started your program: the node executable, the script path, then every argument you typed. Use process.argv.slice(2) to get just your arguments.
- process.envprocess.env is an object holding the environment variables your Node.js program was started with. Every value is a string or undefined, so convert numbers and booleans yourself and give each variable a default.
- Read User InputNode.js has no prompt() function. To ask the user a question in the terminal, create a readline interface on process.stdin and call question(), or await it with readline/promises.
Files and Paths
- fs.readFileRead a file in Node.js with fs.readFile (callback), fs.readFileSync or await readFile from fs/promises. Pass 'utf8' to get a string, handle ENOENT when the file is missing.
- fs.writeFileWrite a file in Node.js with fs.writeFile, fs.writeFileSync or await writeFile from fs/promises. The file is created if it is missing and replaced if it exists; use appendFile to add to the end.
- fs/promisesfs/promises is the promise version of Node's fs module: readFile, writeFile, readdir, stat, mkdir, rm and rename all return promises you await, and errors are caught with try/catch.
- path ModuleThe path module builds and takes apart file paths the right way for the operating system. path.join glues segments together; path.resolve turns them into an absolute path, starting from the current folder.
Asynchronous Node
- Event LoopThe Node.js event loop runs your callbacks in phases (timers, poll, check, close), and between every callback it empties the process.nextTick queue and then the promise queue. Run the examples to see the exact order.
- EventEmitterEventEmitter from Node's events module lets an object announce named events with emit and lets other code react with on or once. Listeners run synchronously, in the order they were added.
HTTP and Express
- HTTP server`http.createServer()` takes one function that runs for every request with `req` and `res`. You read the method and URL from `req`, then set a status, headers and a body on `res` and call `res.end()`.
- Express routingA route in Express is a method, a path and a handler: `app.get('/users/:id', handler)`. Group related routes in an `express.Router()` and mount it under a prefix with `app.use('/api', router)`.
- Express middlewareExpress middleware is a function `(req, res, next)` that runs before your route handler. It can read or change the request, end it with a response, or call `next()` to pass it on.
- req.params, query, body`req.params` holds the named parts of the path (`/users/:id`), `req.query` the query string (`?sort=new`), and `req.body` the parsed request body, which is `undefined` until you add a body parser such as `express.json()`.
- Error handlingAn Express error handler is middleware with four arguments, `(err, req, res, next)`, registered after your routes. Express 5 sends it thrown errors, `next(err)` calls and rejected promises from async handlers.
- express.static`app.use(express.static(path.join(__dirname, 'public')))` serves every file in the `public` folder at the matching URL: `public/style.css` answers `/style.css`. Add a mount path to serve them under a prefix.
- CORS in ExpressA CORS error means the browser blocked a page from reading your API's response because the response did not allow the page's origin. Fix it on the server by sending `Access-Control-Allow-Origin` and answering preflight `OPTIONS` requests, by hand or with the `cors` package.
Data and Auth
- MongoDBUse MongoDB from Node.js with the official mongodb driver: connect with MongoClient, then insert, find, update and delete documents in a collection, all with async/await.
- JWTA JWT is a signed token of three base64url parts that a server issues at login and checks on every request. In Node.js you sign and verify one with the jose or jsonwebtoken package and a secret key.