Skip to content

Instantly share code, notes, and snippets.

@sorindragan
Last active March 26, 2025 05:09
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.

@Whassad181
Copy link

npm run dev

@guest271314
Copy link

@Whassad181

npm run dev

I usually use node without npm on the machine.

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