Node.js is often used to run web servers, and it is possible to run a server on localhost. This can be done with http.createServer
and listen.
By accessing the url property on the request, we can determine the requested file. And we can use this string
to return a page, either from memory or on the disk.
We access the node http module by specifying a require statement at the top of the file. Http contains the createServer
method we need.
http.createServer
and pass an arrow function to it. In this function, we set the statusCode
and call setHeader
.string
from the pages object, with the url as the key.end()
and pass it the string
containing the page content—this is rendered as the page content.listen()
and pass it a port and host name to start the server. A browser can now connect to the localhost server.const http = require("node:http"); // Store all pages with the url string as the key, and the page content as the value. const pages = { "/favicon.ico": "The favicon data", "/": "Start page content", "/about": "About page content" }; // Create a server. const server = http.createServer((req, res) => { // Valid response. res.statusCode = 200; res.setHeader("Content-Type", "text/html"); // Get the response based on the request url. console.log("Requested:", req.url); const output = pages[req.url]; console.log("Output:", output); // Write the output string and end the connection. res.end(output); }); // Start the server. server.listen(8080, "localhost", () => { console.log("Server started"); });Server started Requested: / Output: Start page content Requested: /favicon.ico Output: The favicon data
By accessing the url property within the function argument to http.createServer
, we can access pages and serve them. In this way we can implement an interactive localhost server.