http.createServer Use
This page was last reviewed on 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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 29, 2023 (new).
© 2007-2024 Sam Allen.