Using Node.js as a simple web server

Better Stack Team
Updated on March 11, 2024

Node.js comes with a built-in module called http that can be used to create a simple web server. Below is a basic example of how to create a simple HTTP server using Node.js:

 
const http = require('http');

// Create a server object
const server = http.createServer((req, res) => {
  // Set the response header
  res.writeHead(200, {'Content-Type': 'text/plain'});

  // Send a response
  res.end('Hello, this is a simple Node.js web server!');
});

// Specify the port on which the server will listen
const port = 3000;

// Start the server and listen on the specified port
server.listen(port, () => {
  console.log(`Server running at <http://localhost>:${port}/`);
});

In this example:

  • We import the http module.
  • We create a server using http.createServer(). This function takes a callback function with req (request) and res (response) as parameters. Inside the callback, you handle the incoming request and send the response.
  • We set the response header using res.writeHead() to indicate that the response is plain text.
  • We send a simple text response using res.end().
  • We specify the port (in this case, 3000) on which the server will listen.
  • We start the server with server.listen().

Save the code in a file, for example, server.js, and run it using the following command in the terminal:

 
node server.js

Now, if you open your web browser and navigate to http://localhost:3000/, you should see the message "Hello, this is a simple Node.js web server!".

This is a very basic example, and in a real-world scenario, you might want to use frameworks like Express.js for more features and better organization of your code. However, for a simple use case, the built-in http module is sufficient.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github