Node JS Programs

A. AIM: Create a simple JavaScript file and execute it successfully in Node.js platform.

FirstNodeJS.js

console.log("Program Starts")
let i = 1
while(i<=5){
  console.log(i)
  i++
}
console.log("Program Ends")

OUTPUT:
> node FirstNodeJS.js

Program Starts
1
2
3
4
5
Program Ends

B. AIM: Write a program to show the workflow of JavaScript code executable by creating web server in Node.js.

CreateServer.js

var http = require('http')
var server = http.createServer(function(req,res){
  res.write("Web Server running on 8081 port")
  res.end()
})
server.listen(8081,console.log("Node Server Starts"))

OUTPUT: > node CreateServer.js

Node Server Starts

Now open browser type the following:
localhost:8081

AIM: Write a Node.js module to show the workflow of Modularization of Node application.

MyModule.js

exports.welcome = function(){
  return "Welcome to Node.js modular programming."
}

exports.goodbye = function(){
  return "Good Bye"
}

MainModule.js

var http = require('http')
var mymodule = require('./MyModule')
var server = http.createServer(function(req,res){
  res.write(mymodule.welcome())
  res.write("\n"+mymodule.goodbye())
  res.end()
})

server.listen(8081,console.log("Node server starts on 8081 port number"))

OUTPUT: > node MainModule.js

Node server starts on 8081 port number

Now open browser type the following:
localhost:8081

D. AIM: Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node.

FileOperations.js

var fs = require('fs')
fs.writeFile('mean.txt','Mongo\nExpress\nAngular\nNode',function(error){
  if(error){
    return console.log(error)
  }
})

fs.readFile('mean.txt',function(error,data){
  if(error){
    return console.log(error)
  }
  console.log(data.toString())
})

OUTPUT: > node FileOperations.js

Mongo
Express
Angular
Node