Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Node.js Hello World Example

var http = require("http");

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at https://127.0.0.1:8081/');

Pre-854pm

function determineNum(n)
{
    if(n>=0)
    {
        return 'positive';
    }
    else
    {
        return 'negative';
    }
}

var n1=10;
console.log(determineNum(n1));

var n2=-43;
console.log(determineNum(n2));

function sumCount(numbers)
{
  var sum=0,count=0;
  numbers.forEach(function(number)
  {
      if(number>=0)
      {
          sum=sum+number;
      }
      else
      {
          count=count+1;
      }
  });
  return[sum,count];
}
var numbers=[20,-10,30,-5,10,-20];
console.log(sumCount(numbers));

var n=155;
var randomNumber=Math.round(Math.random() *100);
console.log(randomNumber);

if(n>randomNumber)
{
    console.log('n is greater');
}
else if(n <randomNumber)
{
    console.log('n is lesser');
}
else
{
    console.log('n is equal to randomNumber');
}

function arithematic(a,b,operator)
{
  if(operator==='add')
  {
      return a+b;
  }
  else if(operator==='subtract')
  {
    return a-b;
  }
  else if(operator==='multiply')
  {
    return a*b;
  }
  else if(operator==='divide')
  {
    return a/b;
  }
  else
  {
      return 'operator is not found';
  }
}

console.log(arithematic(5,3,'add'));  
console.log(arithematic(5,9,'*'));

nodejs with DB

/* to connect with db first we need to import that module*/
 var sql= require("./mysql");
var client = sql.createConnection({host:"localhost", user:"root"}); //at this point we can also send the password for db connecttion, ALL CAN PASS DATABASE name.
client.connect();
/*
CLIENT.CONNECT(FUNCTION(ERR){
    IF (ERR){
        RETURN CONSOLE.LOG("CONNECTION FAILED");
    }
    CONSOLE.LOG("CONNECTION SUCCEED");
}
*/


// if db is already created then call
client.query("use bookdb");
// if want to create a new database then call
client.query("create database bookdb", function(err){
	if (err){
		client.end()
		console.log(err);
	}else{
		console.log("Database is created");
	}
	});
client.query("use bookdb");

// NOW CREATE DATABSE tables-----

var sql="CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";

var sql1= "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))";
// sql1 is query with primary key

var sql2 = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
// sql2 is query for insert data.

 var sql3 = "INSERT INTO customers (name, address) VALUES ?";
  var values = [
    ['John', 'Highway 71'],
    ['Peter', 'Lowstreet 4'],
    ['Amy', 'Apple st 652'],
    ['Hannah', 'Mountain 21'],
    ['Michael', 'Valley 345'],
    ['Sandy', 'Ocean blvd 2'],
    ['Betty', 'Green Grass 1'],
    ['Richard', 'Sky st 331'],
    ['Susan', 'One way 98'],
    ['Vicky', 'Yellow Garden 2'],
    ['Ben', 'Park Lane 38'],
    ['William', 'Central st 954'],
    ['Chuck', 'Main Road 989'],
    ['Viola', 'Sideway 1633']
  ];
// sql3 is query for insert data.



 client.query(sql, function(err,result){
     if (err){
         return console.log("table is not created");
     }
     console.log("table has created");
 });
 
 //for sql3
 client.query(sql, [values], function(err,result){
     if (err){
         return console.log("table is not created");
     }
     console.log("table has created with no of rows"+ result.affectedRows);
 });


/* THESE ALL THING RESULTS CONTAINS AFTER EXECUTING QUERY
{
  fieldCount: 0,
  affectedRows: 14,
  insertId: 0,
  serverStatus: 2,
  warningCount: 0,
  message: '\'Records:14  Duplicated: 0  Warnings: 0',
  protocol41: true,
  changedRows: 0
}
*/

/*===============================================*/

/*WHEN WE USE SELECT QUERY THEN WE NEED TO TAKE ONE MORE PARAMETER "fields" IN FUNCTION INSIDE CLIENT.QUERY()  
this fiels give all other details of fetch data
*/


/*===============================================


// 1
 var adr = 'Mountain 21';
  //Escape the address value:
  var sql = 'SELECT * FROM customers WHERE address = ' + mysql.escape(adr);
  
// 2
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result)

// 3
var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result)

*/

/*
DROP TABLE customers
DROP TABLE IF EXISTS customers

============================================================================
SELECT * FROM customers LIMIT 5 = starting 5 rows
SELECT * FROM customers LIMIT 5 OFFSET 2= 5 rows but start from 3rd row.s

*/



















exports.authenticateUser=function(username, password, callback){
	var strQuery="select * from users where username='"+username+"' and password='"+password+"';";
client.query(strQuery,function(err,rows){
	if (err || !rows){
		return callback(err);
	}else if (rows.lenth===0){
		return callback(err);
	}else{
		return callback(null, "success");
	}
});
}
exports.addUser=function(username,password,address,res,callback){
	var strQuery="insert into users values('"+username+"','"+password+"','"+address+"');";
	client.query(strQuery,function(err, saved){
		if (err || !saved){
			return callback(err);
		}
	else{
		callback(null,saved);
	}
	});
}



/*=======================================CONNECT WITH MONGODB====================================================*/




var databasrUrl = "localhost/bookdb";
var collections = ["users","books"] // collections are like tables present in mongoDB.
var db = require("./mongojs");
db.connect(databasrUrl, collections); // this use when already database is created.

db.connect(databasrUrl,function(err,db){
	if(err){
		return console.log("error occured");
	}
	console.log("database is created");
	db.close();
});
var dbo = db.db("mydb"); // name of database
/* 
Important: In MongoDB, a database is not created until it gets content!

MongoDB waits until you have created a collection (table), with at least one document (record) before it actually creates the database (and collection).
 */
 
 db.createCollctions("customers", function(err,result){
	 if(err){
		return console.log("error occured");
	}
	console.log("Collctions is created");
 db.close();}
 );
 db.collection("customers").insertOne({name : "avinash", company : "infosys", address : "Maharamau"},function(err, result){
	 if(err){
		 return console.log("row not inserted");
	 }
	 console.log("data inserted");
	 db.close();
 });
 /* If you try to insert documents in a collection that do not exist, MongoDB will create the collection automatically. */

dbo.collection("customers").find({}).toArray(function(err, result) {
    if (err) throw err; // in this no parameter given in find function
    console.log(result);
    db.close();
  });

//updateCommands
 var myquery = { address: "Valley 345" };
  var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
  dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
    if (err) throw err;
    console.log("1 document updated");
    db.close();
  });

Pre-1236

var rythuBazaar=[
     
     {
         farmerName:'kondaih',
         business:'beetroot'
     },
     
     {
         farmerName:'veeraya',
         business:'chillies'
     },
     
     {
         farmerName:'shivayaa',
         business:'beetroot'
     },
     
     {
         farmerName:'veeren',
         business:'chillies'
     },
     
     {
         farmerName:'raaju',
         business:'beetroot'
     }
];

console.log('Persons who are engaged in beetroot business= ');

for(var i=0;i<rythuBazaar.length;i++)
{
  if(rythuBazaar[i].business==='beetroot')
  {
      console.log(rythuBazaar[i].farmerName);
  }
};

console.log('Farmers engaged in chillies business=');
for(var i=0;i<rythuBazaar.length;i++)
{
    if(rythuBazaar [i].business==='chillies')
    {
        console.log (rythuBazaar [i].farmerName);
    }
}

rythuBazaar.forEach(function(rythuBazaar)
{
    console.log(rythuBazaar);
});

rythuBazaar.forEach(function(rythuBazaar)
{
    if(rythuBazaar.business==='beetroot')
    {
        console.log(rythuBazaar.farmerName);
    }
});

FirstApp

/* Hello, World! program in node.js */
console.log("Hello, World!")

Pre-1132

var babyProduct=[
                  
            {
                name:'doveshampoo',
                color:'cream',
                price:200
            },
            
            {
                name:'himalaya',
                color:'white',
                price:250
            }
];
console.log(babyProduct);
console.log(babyProduct[0]);
console.log(babyProduct[1]);
console.log(babyProduct[0].name);
console.log('Total number of products',babyProduct.length);

for(var i=0;i<babyProduct.length;i++)
{
    console.log(babyProduct[i].name);
}

for(var i=0;i<babyProduct.length;i++)
{
    console.log(babyProduct[i].name + babyProduct[i].color + babyProduct[i].price);
}

ccxxc

function printHello() {
   console.log( "Hello, World!");
}

// Now call above function after 2 seconds
var t = setTimeout(printHello, 2000);

// Now clear the timer
clearTimeout(t);

Precourse-3.js

// camelcasing myIndia='Bharath';

// snakecasingvar my_India='Bharath';

// cobol var _myIndia='Bharath';

var languages=['telugu','tamil','malayalam','kannada'];
console.log(languages);
console.log(languages[0]);
console.log(languages[1]);
console.log(languages[2]);
console.log(languages[3]);
console.log(languages[4]);

var carNames=['hyundia','tata','bmw','renault'];
console.log(carNames);
console.log(carNames.length);
carNames.push('toyoto');
console.log(carNames);
carNames.unshift('ford');
console.log(carNames);
carNames.pop();
console.log(carNames);
carNames.shift();
console.log(carNames);
console.log(carNames.length);
console.log(carNames.includes('mercendres'));
console.log(languages.includes('hindi'));
console.log(languages.includes('tamil'));
//array-loop
var cementCompanies=['zuari','binami','dalmia','priya'];
console.log(cementCompanies);
for(var i=0;i<cementCompanies.length;i++)
{
    console.log(i,cementCompanies[i]);
}
for(var i=0;i<carNames.length;i++)
{
    console.log(i,carNames[i]);
}

for(var i=0;i<languages.length;i++)
{
    console.log(i,languages[i]);
}


Pre-course 1

function greeting(name)
{
    return 'Welcome to'+cityName;
}
var cityName='Bangalore';
console.log(greeting(cityName));

function evenOdd(number)
{
    if(number%2===0)
    {
        return 'even';
    }
    else
    {
        return 'odd';
    }
}
console.log(evenOdd(12));
console.log(evenOdd(15));

function addSum(p1,p2)
{
 return p1+p2;
}
var s1=25;
var s2=21;
console.log(addSum(s1,s2));

function sumArray(numbers)
{
 var sum=0;
 if(numbers.length===0)
 {
     return 0;
 }
 for(var i=0;i<numbers.length;i++)
 {
     if(numbers[i]>0)
     {
       sum=sum+numbers;
     }
     return sum;
 }
}
var numbers=[];
console.log(sumArray(numbers));

function isDivisible(n,x,y)
{
  if((n%x===0) &&(n%y===0))
  {
     return true;
  }
  else
  {
      return false;
      
  }
}
console.log(isDivisible(10,2,5));
console.log(isDivisible(21,7,2));

var liquidName;
console.log(liquidName);
var liquidName='Surf excel matic';
console.log(liquidName);

var liquidName1='Ariel matic';
var quantity=1.02;
var types=[1,2.5,6,8.9];
var mode=['top','front','normal'];
var productNumber='SF25FG';

Quick Sort in Node js

var myArray = [3, 0, 2, 5, -1, 4, 1 ];

function quickSort(arr){
    var finalArray = [];
    if(arr.length <= 1){
        return arr
    }
    var midIndex = parseInt(arr/2);
    var pivot = arr.pop();
    var leftArray = [], rightArray = []; 
    for(var i= 0; i< arr.length; i++){
        if(arr[i] <= pivot){
            leftArray.push(arr[i]);
        }else{
            rightArray.push(arr[i])
        }
    }
   // console.log('left Array : ', leftArray, 'rightArray :', rightArray, 'pivot : ', pivot);
    return finalArray.concat(quickSort(leftArray), pivot, quickSort(rightArray));
    
}
console.log("Original array: " + myArray);
var sortedArray = quickSort(myArray);
console.log("Sorted array: " + sortedArray);

Previous 1 ... 4 5 6 7 8 9 10 ... 90 Next
Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.