Skip to main content
simple-node-hello-example

Getting Started with nodejs Application

This tutorial help to setup a simple node application and demo on Ubuntu operating system. This nodejs example will show 'Hello! First node application' message on https://localhost:3000.

I am creating this example on Ubuntu Linux, So all commands you see would be entered in your Terminal with $ symbol. You need to install nodejs on your Ubuntu Machine. You can install nodejs by following this article or by using the below steps.

How to install Nodejs in Ubuntu

Command will update the Linux box
sudo apt-get update
install nodejs
sudo apt-get install nodejs
install node package manager
sudo apt-get install npm

How to check nodejs version, You can run the following command to see the installed node version
$node -v

Simple Hello World Nodejs Example

simple-node-hello-example

Step 1: We will create a new folder for this project and change it into that directory.

$ mkdir hello-app
$ cd hello-app

Step 2: We will create package.json file for this node.js application. This file defines what libraries or modules will be used in this nodejs project, we can create package.json file by using the below command:

~/hello-app$  npm init

You need to enter some input like project name, version and entry point etc, You just pressed enter on and finally you will have a package.json file in your folder. The command window will look like below,

Press ^C at any time to quit.
name: (hello-app)
version: (1.0.0)
description:
entry point: (main.js)
test command:
git repository:
keywords:
author: adam
license: (ISC)
About to write to $hello-app\package.json:

{
  "name": "hello-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "adam",
  "license": "ISC"
}


Is this ok? (yes)

The main.js is our main node server project entry file. I am creating a simple 'Hello! First node application' application so we don’t have any dependency node modules for this nodejs project.

Step 3: We will create main.js file using the below command.

~/hello-app $ vi main.js

and now write the below js code into this file.

var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello! First node appliaction\n');
}).listen(3000);

console.log('Server started');

Step 4: Now save your main.js file and run nodejs app using below command:

~/hello-app$ node main.js

You should see 'Server started' in the terminal, Now open your web browser and go to 'https://localhost:3000' url, you should see your 'Hello! First node application' message in the browser.

Leave a Reply

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