Getting Started With Node – Course

Creating a Simple Web App in Node

Let’s build a simple Web application that prints Hello World on the browser upon user’s request.

We will use the native http module of Node to achieve the Web Server functionality.

Here is the code:

const http = require('http');

const hostname = 'localhost';
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}/`);

Copy the code and past it in a new file. Name the file as hello.js and save it.

To run this code, open your terminal and switch to the location where you have stored the file.

Run this command to execute your code.

node hello.js

You should the following message on the terminal.

Node hello world

Open your browser and type localhost:3000 and hit enter. You should see the following message.

Node Hello World

That’s it. You have just developed your first Node program. Congratulations!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.