Home
Node.js
http.createServer Use
Updated Dec 29, 2023
Dot Net Perls
Http. 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.
Example. We access the node http module by specifying a require statement at the top of the file. Http contains the createServer method we need.
Object
Start We call http.createServer and pass an arrow function to it. In this function, we set the statusCode and call setHeader.
Next We access the url property on the request argument. Then we access a string from the pages object, with the url as the key.
Then We call end() and pass it the string containing the page content—this is rendered as the page content.
Finally We call 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 29, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen