Nodejs for beginners: Creating An HTTP server using Plain Node JS
If you are just starting out with Node.js, one of the first things you will want to learn is how to create an HTTP server using plain Node.js. This is a fundamental skill that will serve as the basis for many of your future Node.js projects.
Creating an HTTP server using plain Node.js is actually quite simple. In fact, it only requires a few lines of code. Here’s a step-by-step guide to help you get started:
Step 1: Install Node.js
If you haven’t already installed Node.js, you will need to do so in order to follow along with this tutorial. You can download and install Node.js from the official Node.js website.
Step 2: Create a new file
Open your favorite text editor and create a new file. You can name this file anything you like, but for the purposes of this tutorial, let’s call it server.js
.
Step 3: Write your server code
Now, it’s time to write the actual code for your HTTP server. In your server.js
file, type the following code:
“`javascript
// Import the ‘http’ module
const http = require(‘http’);
// Create a server
const server = http.createServer((req, res) => {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘Hello, World!n’);
});
// Start the server
server.listen(3000, ‘127.0.0.1’, () => {
console.log(‘Server running at http://127.0.0.1:3000/’);
});
“`
Step 4: Save your file and run your server
Now that you’ve written your server code, save your server.js
file and navigate to its location in your terminal or command prompt. Then, run the following command to start your server:
“`bash
node server.js
“`
If everything is working as expected, you should see a message in your terminal that says “Server running at http://127.0.0.1:3000/”. Congratulations, you’ve just created your very own HTTP server using plain Node.js!
Now that your server is up and running, you can visit http://127.0.0.1:3000/ in your web browser to see your server in action. You should see a simple “Hello, World!” message displayed on the page.
With just a few lines of code, you’ve learned how to create an HTTP server using plain Node.js. This is just the beginning of what you can do with Node.js, so be sure to keep exploring and learning new techniques as you continue your journey with this powerful JavaScript runtime.