Tuesday, February 14, 2017

How to create a simple web server using Nodejs

Example#

An example of a web server written with Node.js which responds with 'Hello World':
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
To run the server, put the code into a file called example.js and execute it with Node.js:
$ node example.js
Server running at http://127.0.0.1:3000/

No comments:

Post a Comment