• Register

Share:- Whatsapp Facebook Facebook

------------------------------------- Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

0 votes
40 views
How to create a simple server in Node.js ?
in Node.js by

1 Answer

0 votes
For Creating a Node.js server follows the following steps:-

Step 1:- Import required module like:- http
var http = require("http");

We use the require directive to load the http module.

Step 2:- Create Node.js Server:-We use the created http variable with createServer() function to create a node.js server instance. And bind with port 3000 by listen() method.

Code for creating node.js server:-
http.createServer(function (request, response) {
   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Welcome to node.js"
   response.end('Welcome to node.js\n');
}).listen(3000);

// Console will print the message
console.log('Server running at http://127.0.0.1:3000/');

Step 3:- Run node.js server by using node command.
$ node main.js (File name)

Step 4:- Output will come on console:-
Server running at http://127.0.0.1:3000/

Step 5:- Open your web browser and type http://127.0.0.1:3000/ then you will get the output on browser like:- "Welcome to node.js"
by (3.3k points)
...