Node.js is a JavaScript runtime that allows you to build server-side applications with JavaScript. In this guide, we'll walk you through the steps to create a simple HTTP server using Node.js.
First, open your terminal and create a new directory for your Node.js project. You can do this by running the following command:
mkdir node-server
cd node-serverThis creates a new directory called node-server and navigates into it.
Before creating the server, it's a good idea to initialize a package.json file to keep track of your dependencies. Run this command to generate a package.json file:
npm init -yThis will create a default package.json file in your project directory, which you can later edit to add dependencies.
Next, you'll create a new JavaScript file where you'll write the code for your Node.js server. In your terminal, run:
touch app.jsThis command will create a new file named app.js.
Open app.js in your preferred text editor and add the following code to create a basic HTTP server.
var http = require("http");
var server = http.createServer(function (req, res) {
res.write("Hello World!");
res.end();
});
server.listen(5000);
console.log("Node.js web server at port 5000 is running..");To run this command:
node app.jsOutput:
Node.js web server at port 5000 is running..Code breakdown step by step
var http = require("http");
var server = http.createServer(function (req, res) {
res.write("Hello World!");
res.end();
});
server.listen(5000);
console.log("Node.js web server at port 5000 is running..");http)http.createServer(...)res.write("Hello World!"); res.end();)server.listen(5000))