Simple node program (Part-3)

Akash Jadhav
2 min readJun 4, 2019

--

Introduction -
In this tutorial we will write a simple node.js program for addition of two numbers, to make you understand how the variables, functions and arithmetic operators function in node.js

If you need the list of all node.js tutorials available and their end results follow the link below -
Node.js Tutorials Summary (Part-0)
https://medium.com/@akash_jadhav/node-js-tutorials-part-0-a48b44bb3b6e

If you haven’t checked out my previous tutorial about Getting started with Node.js (Part-2) follow the link below -
https://medium.com/@akash_jadhav/getting-started-with-node-js-305ca4e5ab55

Note:
1) If you have not setup your node.js environment I would suggest you to view THIS tutorial to get setup with your machine.
2) Follow each step and go through its description to not only make your program running but also to understand it in detail.
3) All commands are to be executed on ‘terminal’. (Ubuntu terminal is used this below tutorial)
4) Link to code files on Github here -
https://github.com/AkashJadhav-github/node-projects

Follow the steps below to understand and execute the program -

Step 1) — Create a new file and name it as addition.js
Paste the below code in it -

var http = require(‘http’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});
res.end(‘Hello World!’);
}).listen(8080);

Step 2) — Now as we have done with basic setup of node program, for addition of two numbers we will declare two variables in our javascript code.

var http = require(‘http’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});

var number1 = 1;
var number2 = 2;

res.end(‘Hello World!’);
}).listen(8080);

Step 3) — Now its time to add the two numbers, for now lets keep it simple and add these numbers in third variable.

var http = require(‘http’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});

var number1 = 1;
var number2 = 2;

var sum;
sum = number1 + number2

res.end(‘Hello World!’);
}).listen(8080);

Step 4) — As we want this sum to return in the response object (or to get the output in the browser) we need to pass it in res.end()

var http = require(‘http’);

http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/html’});

var number1 = 1;
var number2 = 2;

var sum;
sum = number1 + number2

res.end(‘Sum = ’+sum);
}).listen(8080);

Now run the node file (cmd -> node addition.js) and open the URL — localhost:8080 in your favourite browser. And tada! you got an output as
Sum=3"
Now I want you to try for Multiplication, Division and Subtraction of different numbers and comment me link to your code.
If you like it do clap and hey, Happy Nodeing!!

--

--