Show List
Sample Node js Program
Node.js provides run time environment to execute JavaScript code. You can put the code in a file with .js extension and execute it using command line or through Visual Studio code. For example here is a sample JavaScript Code. Save this code in demo.js file:
Example 1
var a = 5;var b = 4;var sum = a + b;console.log("Sum of the numbers is " + sum);
You can use command line to run this JavaScript code:
C:\Users\mail2\Downloads\Sample>node demo.js Sum of the numbers is 9
Here is the screenshot of running the same code through VS Code.
Example 2
In this example, we are going to use local module using one JavaScript file and load it into another JavaScript file using require function.
Local module: calculatorFn.js
function add(a, b) {return a + b;}function subtract(a, b) {return a - b;}function multiply(a, b) {return a * b;}function divide(a, b) {return a / b;}exports.add = addexports.subtract = subtractexports.multiply = multiplyexports.divide = divide
demo.js
const mod = require('./myModule');const calc = require('./calculatorFn');var a = 5;var b = 4;console.log("Sum of the numbers is " + calc.add(a,b));console.log("Difference of the numbers is " + calc.subtract(a,b));console.log("Multiplication of the numbers is " + calc.multiply(a,b));console.log("Division of the numbers is " + calc.divide(a,b));
Results:
Source Code:
https://github.com/it-code-lab/nodejs-sample-program
Leave a Comment