Monday 4 March 2019

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

Question: What is callback?
A callback function is called at the completion of a given task.


Question: What Are Arrow Functions?
Arrow functions – also called "fat arrow" functions, are a more concise syntax for writing function expressions.

Examples
const multiplyES6 = (x, y) => { return x * y };
const phraseSplitterEs6 = phrase => phrase.split(" ");
var docLogEs6 = () => { console.log(document); };



Question: What is JSON.stringify()?
JSON.stringify() method converts a JavaScript object to a JSON string.


Question: What is Handlebars view engine in nodejs?
Handlebars.js is templating engine in NodeJS.


Question: What is an error-first callback?
Error-first callbacks are used to pass errors and data.
You have to pass the error as the first parameter, and it has to be checked to see if something went wrong.


Question: What are Promises?
The Promise object represents the event completion or failure of an asynchronous operation, and its resulting value.
function readFile(filename, enc){
  return new Promise(function (resolve, reject){
    fs.readFile(filename, enc, function (err, res){
      if (err) reject(err);
      else resolve(res);
    });
  });
}



Question: What is callback hell in Node.js?
Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain.


Question: What is the role of REPL in Node.js?
Full form of REPL is Read Eval print Loop.


Question: Explain chaining in Node.js?
Chaining is a mechanism whereby the output of one stream is connected to another stream as input.


Question: How to access the GET parameters after ? in Express?
req.query.name;



Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers.


Question: How we exporting a Module?
We use export for exporting the module.
exports.sayHelloInEnglish = function() {
    return "Hello, how are you?";
};



Question: What is meaning of tilde and caret?
the tilde(~) matches the most recent minor version.
the caret(^) matches the most recent major version.


Question: How to access 2nd argument when passed in command line?
process.argv.slice(3,4); //two=222



Question: What is Yargs?
Yargs helps to parsing arguments of command line tools.



Question: What is Async?
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
    // results is now an array of stats for each file
});



Question: How to use expressJs in Node
var express = require('express');
var app = express();

//Add cookie to express
var cookieParser = require('cookie-parser');
app.use(cookieParser());

//Add session to express
var session = require('express-session');
app.use(session({
    secret: 'XEDDKJKXD',
    name: 'testname',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));

//Add static path
app.use(express.static('public'))

//Add "Parse JSOn" to express
var bodyParser = require('body-parser')
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
    extended: true
}));

//Add middleware to express
app.use(function (req, res, next) {
  //console.log('Time2222:', Date.now())
 res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   
  next()
})


//Add https to expresJs
var https = require('https');
var privateKey  = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/georama.crt', 'utf8');
var caCertificate = fs.readFileSync('public/cert/chain.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate, ca: caCertificate};
var httpsServer = https.createServer(credentials, app);   


Question: How to start node on port?
httpsServer.listen(config['SERVERPORT'],function() {
    console.log('https listening on *:' + config['SERVERPORT']);
});



Question: How to connect socket with https?
var io = require('socket.io')(httpsServer);



Question: What is underscore module in nodeJS?
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: What Are Core Features Of Express Framework?
1) Allows to set up middlewares to respond to HTTP Requests.
2) Defines a routing.
3) Dynamically render HTML Pages.


Question: Give simple example of ExpressJS?
var app = require('express')();
var http = require('http').Server(app);

app.get('/listing', function (req, res) {   
   res.send('This is listing API'); 
});

http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: What are different Middleware?
1) Application-level middleware
2) Router-level middleware
3) Error-handling middleware
4) Built-in middleware
5) Third-party middleware



Wednesday 13 February 2019

PHP 7 interview Questions and Answers

PHP 7 interview Questions and Answers

Question: What is class Constants?
You can define constant as string OR expression within the class. but you can not define class as variable, or function.


Question: When will Autoloading function will be called once defined?
a) spl_autoload_register (autoload) will called when create object of class.
b) spl_autoload_register will called when extend by any class (using extends).
c) spl_autoload_register will called when implements an interface (using implements ).


Question: What is visibility? What are different type of visibility in class?
visibility means setting the access level of data member and member function.
Class methods must be declare as public, protected or private.
You can also declare with var which means public


Question: What is Static Keyword?
Declaring class property or methods as static makes them accessible without needing an instantiation of the class.
$this is not available inside the function.


Question: Tell me about Abstraction in PHP?
  1. Classes defined as abstract may not be instantiated.
  2. Class that contains at least one abstract method must also be abstract.
  3. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child.
  4. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.



Question: Tell me about Interface in PHP?
  1. We use "interface" keyword to create class.
  2. All methods declared in an interface must be public.
  3. To implement an interface, the implements operator is used.
  4. We can include multiple interface while implementing



Question: Tell me about Traits in PHP?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
We can't create instance of a traits
We can create Traits as below
    
trait Hello {
        public function sayHello() {
            echo 'Hello ';
        }
    }
We can use multiple traits using comma like below
 use Hello, World;
When two traits have same function, it would conflict but we can fix using insteadof like below
A::bigTalk insteadof B;
We can set the visibility of function using "as" like below
use HelloWorld { sayHello as protected; }
We can use one trait from another using "use"
we can also define abstract,static, data members, method


Question: Tell me about Anonymous classes?
We can create a class without specifing the class-name. Following are example
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});


Question: What is Overloading in PHP?
Overloading in PHP provides means to dynamically create properties and methods.
These dynamic entities are processed via magic methods one can establish in a class for various action types.
example of magic functions __get(), __set(), __isset(), __unset(), __call(),__callStatic() etc