Skip to content

Instantly share code, notes, and snippets.

@sorindragan
Last active July 17, 2024 20:41
Show Gist options
  • Save sorindragan/f8bba53b7c16a28ae4e12460c911b503 to your computer and use it in GitHub Desktop.
Save sorindragan/f8bba53b7c16a28ae4e12460c911b503 to your computer and use it in GitHub Desktop.
Simplest node.js http server (http://localhost:3000)
const http = require('http')
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end("Running")
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if(err) {
return console.log("Error", err)
}
console.log(`Listening on port ${port}`)
})
@web-apply
Copy link

web-apply commented May 3, 2023

To create the simplest Node.js HTTP server, follow these steps:

Open a new file in your code editor of choice and save it with a .js extension, for example, "server.js".
In the server.js file, add the following code:

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Save the server.js file and open a terminal or command prompt window in the same directory as the file.
Run the server by typing node server.js in the terminal or command prompt window.
Open a web browser and navigate to http://localhost:3000/ to see the server running.
The code above creates a simple HTTP server that listens on port 3000 of the localhost. When a request is made to the server, it responds with a status code of 200 and a plain text response of "Hello, World!". You can modify the response to suit your needs or serve different types of content, such as HTML, CSS, or JSON.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment