Monday, 23 October 2017

javascript object and array example

var obj={};
undefined
var arraydata=[];
undefined
arraydata.push(obj);
1
arraydata
[Object]0: Objectlength: 1__proto__: Array[0]
arraydata.push(obj={name:"pawan",age:"26"});
2
arraydata
Array[2]0: Object1: Objectage: "26"name: "pawan"__proto__: Objectlength: 2__proto__: Array[0]
for(var i=0;i< arraydata.length;i++)
{

console.log(arraydata[i].name);

}
VM1178:4 undefined
VM1178:4 pawan
undefined
obj
Objectage: "26"d: Array[4]name: "pawan"__proto__: Object
obj.d=[];
Array[0]length: 0__proto__: Array[0]
d=['name','address','lion'];
Array[3]0: "name"1: "address"2: "lion"length: 3__proto__: Array[0]
obj
Objectage: "26"d: Array[0]length: 0__proto__: Array[0]name: "pawan"__proto__: Object
obj.d
[]
d1=['dff','fggftt','uio'];
Array[3]0: "dff"1: "fggftt"2: "uio"3: "pawan"length: 4__proto__: Array[0]
obj.d1
undefined
obj.d=d1;
["dff", "fggftt", "uio"]0: "dff"1: "fggftt"2: "uio"3: "pawan"length: 4__proto__: Array[0]
obj
Objectage: "26"d: Array[3]0: "dff"1: "fggftt"2: "uio"length: 3__proto__: Array[0]name: "pawan"__proto__: Object
obj.d1.push("pawan");
VM1347:1 Uncaught TypeError: Cannot read property 'push' of undefined
    at <anonymous>:1:7
(anonymous) @ VM1347:1
obj.d.push("pawan");
4
obj
Objectage: "26"d: Array[4]0: "dff"1: "fggftt"2: "uio"3: "pawan"length: 4__proto__: Array[0]name: "pawan"__proto__: Object

Monday, 16 October 2017

Example of callback function example in nodejs

var express = require('express');
var router = express.Router();
var callbackexp={};


router.get('/',function(req,res)

{



console.log("data1");
var example=function (data1)
{
console.log("2");
var data="example";

var ingo=data+data1;
//return ingo;
res.send(ingo);
//console.log(ingo);
}

var infodata=function (callback)
{
console.log("1");
var data="pawank umar";
callback(data);

}
infodata(example);
console.log("3");
res.send("op");
//res.send("hello"+data);




});



module.exports=router;

Saturday, 14 October 2017

bluebird implementation in nodejs

https://www.guru99.com/bluebird-promises.html


Bluebird is a fully-featured Promise library for JavaScript. The strongest feature of Bluebird is that it allows you to "promisify" other Node modules in order to use them asynchronously. Promisify is a concept applied to callback functions. This concept is used to ensure that every callback function which is called returns some sort of value.
So if a Node JS module contains a callback function which does not return a value, if we Promisify the node module, all the function's in that specific node module would automatically be modified to ensure that it returns a value.
So you can use BlueBird to make the MongoDB module run asynchronously. This just adds another level of ease when writing Node.js applications.
We will look at an example of how to use the bluebird module.
Our example will first establish a connection to the "Employee collection" in the "EmployeeDB" database. If "then" connection is established, then it will get all of the records in the collection and display them in the console accordingly.

Generating promises with the BlueBird library

Step 1) Installing the NPM Modules
To use Bluebird from within a Node application, the Bluebird module is required. To install the Bluebird module, run the below command
npm install bluebird
Step 2) The next step is to include the bluebird module in your code and promisify the entire MongoDB module. By promisify, we mean that bluebird will ensure that each and every method defined in the MongoDB library returns a promise.
Bluebird Promises Tutorial
Code Explanation:-
  1. The require command is used to include the Bluebird library.
  2. Use Bluebird's .promisifyAll() method to create an async version of every method the MongoDB module provides. This ensures that each method of the MongoDB module will run in the background and ensure that a promise is returned for each method call in the MongoDB library.
Step 3) The final step is to connect to our database, retrieve all the records in our collection and display them in our console log.
Bluebird Promises Tutorial
Code Explanation:-
  1. You will notice that we are using the "connectAsync" method instead of the normal connection method for connecting to the database. Bluebird actually adds the Async keyword to each method in the MongoDB library to distinguish those calls which return promises and those which don't. So there is no guarantee that methods without the Async word will return a value.
  2. Similar to the connectAsync method, we are now using the findAsync method to return all of the records in the mongoDB 'Employee' collection.
  3. Finally, if the findAsync returns a successful promise we then define a block of code to iterate through each record in the collection and display them in the console log.
If the above steps are carried out properly, all of the documents in the Employee collection will be displayed in the console as shown in the output below.
Bluebird Promises Tutorial
Here is the code for your reference
var Promise = require('bluebird');

var mongoClient = Promise.promisifyAll(require('mongodb')).MongoClient;

var url = 'mongodb://localhost/EmployeeDB';
mongoClient.connectAsync('mongodb://localhost/EmployeeDB')

.then(function(db) {
        return db.collection('Employee').findAsync({})

    })
    .then(function(cursor) {
        cursor.each(function(err, doc) {
            console.log(doc);
        })
    }); 

funtions

https://lodash.com/docs/

import and export in nodejs link

https://hackernoon.com/import-export-default-require-commandjs-javascript-nodejs-es6-vs-cheatsheet-different-tutorial-example-5a321738b50f


https://www.npmjs.com/package/import-export


https://medium.com/the-node-js-collection/an-update-on-es6-modules-in-node-js-42c958b890c

Thursday, 12 October 2017

callback example

https://stackoverflow.com/questions/19739755/nodejs-callbacks-simple-example

Wednesday, 11 October 2017

Tuesday, 10 October 2017

Monday, 9 October 2017

magic function link

https://www.techflirt.com/tutorials/oop-in-php/magic-methods-in-php.html
https://lornajane.net/posts/2012/9-magic-methods-in-php

event emitter example

// Import events module
var events = require('events');


// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');
  
   // Fire the data_received event 
   eventEmitter.emit('data_received');
}

// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
 
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
   console.log('data received succesfully.');
});

// Fire the connection event 
eventEmitter.emit('connection');

console.log("Program Ended.");

express js skeleten

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/employee')
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err));

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users',users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

var http = require('http');

//create a server object:
//app.listen
app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

module.exports = app;

Thursday, 5 October 2017

what is bodyparser extended true and false in nodejs

https://stackoverflow.com/questions/29960764/what-does-extended-mean-in-express-4-0


If extended is false, you can not post "nested object"
person[name] = 'cw'

// Nested Object = { person: { name: cw } }
If extended is true, you can do whatever way that you like.

what is traits in php (multipale interface )

https://www.sitepoint.com/using-traits-in-php-5-4/

Tuesday, 3 October 2017

method overload example in php

<?php
class TDshape {
const Pi = 3.142 ;  // constant value
 function __call($fname, $argument)
 {
    if($fname == 'area')
    {
        switch(count($argument))
    {
            case 0 : return 0 ;
            case 1 : return self::Pi * $argument[0] ; // 3.14 * 5
            case 2 : return $argument[0] * $argument[1];  // 5 * 10
    }
    }
}
}
$circle = new TDshape();
echo "Area of circle:".$circle->area(5)."</br>"; // display the area of circle
 $rect = new TDshape();
echo "Area of rectangle:".$rect->area(5,10); // display area of rectangle

?>