Thursday, April 13, 2017

Node js Tutorial for beginners with examples

Question: How do I pass command line arguments? and how i get the arguments?
Pass argument through Command line

node main.js one two=three four

Script to read value from command line
process.argv.forEach(function (val, index, array) {
console.log(index + '=> ' + val);
});
Output
0=> node
1=> /data/node/main.js
2=> one
3=> two=three
4=> four



Question: How can we debug Node.js applications?
Install node-inspector
npm install -g node-inspector



Question: How to debug application through node-inspector
node-debug app.js



Question: What is the purpose of Node.js module.exports?
module.exports is the object that's run as the result of a require call.
file: main.js
var sayHello = require('./sayhellotoworld');
sayHello.run(); // "Hello World!"

sayhellotoworld.js
exports.run = function() {
console.log("Hello World!");
}



Question: How to exit in Node.js?
process.exit();

End with specific code.
process.exit(1);



Question: Read environment variables in Node.js?
process.env.ENV_VARIABLE



Question: How to pars a JSON String?
var str = '{ "name": "Web technology experts notes", "age": 98 }';
var obj = JSON.parse(str);



Question: How to get GET (query string) variables in Node.js?include the "url" module
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);



Question: How to get GET (query string) variables in Express.js?
var express = require('express');
var app = express();

app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});



Question: How to make ajax call in nodeJS?
var request = require('request');
request.post(
'http://www.example.com/action',
{ json: { name: 'web technology experts',age:'15' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
 
Question: How to print a stack trace in Node.js?

console.trace("print me")






Question: How can I get the full object in Node.js's console.log()?

const util = require('util');
console.log(util.inspect(myObject, false, null))







Question: How to use jQuery with Node.js?

First instal the jquery then use as following.


require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}

var $ = require("jquery")(window);
});







Question: How to change bower's default components folder?

Create a .bowerrc file in root and add following code.

{
"directory" : "public/components"
}






Question: How to encode base64 in nodeJS?

console.log(new Buffer("hello").toString('base64')); //aGVsbG8=







Question: How to decode base64 in nodeJS?

console.log(new Buffer("aGVsbG8=", 'base64').toString('ascii')); //hello







Question: How to get listing of files in folder?

const testFolder = './files/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
})







Question: How do you extract POST data in Node.js?

app.use(express.bodyParser());
app.post('/', function(request, response){
console.log(request.body.user.fname); //print first name
console.log(request.body.user.lname); //print last name
});






Question: How to remove file nodeJS?

var fs = require('fs');
var filePath = '/folder/arun.docx';
fs.unlinkSync(filePath);







Question: How to access the GET parameters after ? in Express?

var email = req.param('email');





Question: How to copy file in nodeJS?

var fs = require('fs');
fs.createReadStream('existing.txt').pipe(fs.createWriteStream('new_existing.txt'));







Question: How to append string in File?

var fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {

});






Question: How to get version of package?

var packageJSON = require('./package.json');
console.log(packageJSON.version);







Question: What is express js?

Express.js is a NodeJS framework.

It is designed for building single-page, multi-page, and hybrid web applications.





Question: How to Send emails in Node.js?

You can use node-email-templates.

https://github.com/crocodilejs/node-email-templates





Question: How to get Ip Address of client?

request.connection.remoteAddress
 
Question: How to check if path is file or directory?

var fs = require("fs");
console.log(fs.lstatSync('/file').isDirectory()); //true/false



Other useful commands

fs.lstatSync('/file').isFile();
stats.isDirectory().isBlockDevice();
stats.isDirectory().isCharacterDevice();
stats.isDirectory().isSymbolicLink() (only valid with fs.lstat());
stats.isDirectory().isFIFO();
stats.isDirectory().isSocket();







Question: How to create a new directory? If does not exist.

var fs = require('fs');
var dir = '/log_folder';

if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}



Question: How do I URl Encode in Node.js?

for this, you can use encodeURIComponent (JS function)


encodeURIComponent('select * from table where i()')







Question: How do POST data in an Express JS?

for this, you must install express using "npm install express"


var express = require('express') , app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(request, response){
console.log(request.body);
response.send(request.body);
});
app.listen(3008);








Question: How to output pretty html in Express?

for this, you must install express using "npm install express"


app.set('view options', { pretty: true });







Question: How to setup cron in NodeJS?

https://github.com/kelektiv/node-cron







Question: How to setup Logging in NodeJS?

  1. Install log4js
    npm install log4js
  2. Configuraiton ./config/log4js.json)
    {"appenders": [
    {
    "type": "console",
    "layout": {
    "type": "pattern",
    "pattern": "%m"
    },
    "category": "app"
    },{
    "category": "test-file-appender",
    "type": "file",
    "filename": "log_file.log",
    "maxLogSize": 10240,
    "backups": 3,
    "layout": {
    "type": "pattern",
    "pattern": "%d{dd/MM hh:mm} %-5p %m"
    }
    }
    ],
    "replaceConsole": true }
  3. Log data
    var log4js = require( "log4js" );
    log4js.configure( "./config/log4js.json" );
    var logger = log4js.getLogger( "test-file-appender" );
    logger.debug("Hello");//debug
    logger.info("Info logs"); //info
    logger.error("Error logs") //error

Question: How redis works with NodeJS?
for this, you must install Redis
npm install redis
Include redis in code
redis = require('redis');
Create Redis object
var clientRedis = redis.createClient('6379', '127.0.0.1');
Save the data in Redis
clientRedis.hset("users", '10', 'roberts'); //Name, key, value
Delete the data from redis
clientRedis.del("users", 10);


Question: How to get current date in Nodejs?
new Date().toISOString();// '2016-11-04T14:51:06.157Z'
 

Express js Interview questions and answers

Question: How to install express js in node?
use following command to install express js.

npm install express



Question: How to use express js in node?
use require to include express module.
var app = require('express')();



Question: How to use handle get request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (req, res) {
console.log("Got a GET request for the homepage"); //Shown in console
res.send('This is GET Method for Homepage'); //Display as response
})

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



Question: How to use handle post request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.post('/user_list', function (req, res) {
console.log("Got a POST request for the user_list URL"); //Shown in console
res.send('This is POST Method for user_list URL');//Display as response
})

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



Question: How to use handle GET/POST request for same URL expressJs?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

//This is POST Request
app.post('/add_user', function (req, res) {
console.log("Got a POST request for the add_user URL"); //Shown in console
res.send('This is POST Method for add_user URL');//Display as response
})

//This is Get Request
app.get('/user_list', function (req, res) {
console.log("Got a GET request for the user_list URL"); //Shown in console
res.send('This is GET Method for user_list URL');//Display as response
})

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



Question: How to use handle GET request for all URL start with ab* ?
app.get('/ab*', function(req, res) {   
console.log("Got a GET request for /ab*");
res.send('Page Regex Match');
})
Question: How to send Server call in Node?
Install the "request" module with following command.
npm install request

Include the request module in page, and send the request to server.
request = require('request');
request( "http://exmaple.com:8081:/users/add/?n=test&p=2277585&email=test@gmail.com", function(err, res, body) {
console.log(res);
console.log(body);
});




Question: How to post data and get in express Js?
HTML Code
<form action="http://example.com:8081/register" method="GET">
Name: <input name="name" type="text" /> <br />
Email: <input name="email" type="text" />
Phone: <input name="phone" type="text" />
<input type="submit" value="Submit" />
</form>


Express JS Code
app.get('/register', function (req, res) {   
response = {
name:req.query.name,
email:req.query.email
phone:req.query.phone
};
console.log(response);
res.end(JSON.stringify(response));
})



Question: How to get cookie in Express js?
Install the "cookie-parser" module with following command.
npm install cookie-parser

Include the cookie-parser, in node.
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})


Question: How Static Files works in Express js?
Static files are images/videos/css/js etc.
For this, first you need to set the folder path using "express.static" method. See Example
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello ');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
})



Question: How to upload images in Express js?
HTML Code
<form action="http://example.com:8081/file_upload" enctype="multipart/form-data" method="POST">
<input name="file" size="50" type="file" />
<input type="submit" value="Submit" />
</form>

ExpressJS Code
var fs = require("fs");
var express = require('express');
var app = express();
var fs = require("fs");

app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
var destinationFile = __dirname + "/images/" + req.files.file.name;

fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(destinationFile, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully in '+destinationFile,
filename:req.files.file.name
};
}
//console.log( response );
res.end( JSON.stringify( response ) );
});
});
})



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete

PHP Interview Questions and Answers for Experience

Question: What is use of header() function in php?
1. Header is used to redirect from current page to another:

header("Location: newpage.php");

2. Header is used to send HTTP status code.
header("HTTP/1.0 404 Not Found");

3. Header is used to send Send a raw HTTP header
header('Content-Type: application/pdf');



Question: What type of inheritance supports by PHP?
There are following type of inheritance
Single Inheritance - Support by PHP
Multiple Inheritance - Not support
Hierarchical Inheritance - Support by PHP
Multilevel Inheritance - Support by PHP


Question: How do you call a constructor for a parent class?
parent::constructor($value);



Question: What is the difference between the functions unlink and unset?
unlink: It is used to remove the file from server.
unlink('/path/file.phtml');

unset: It is used to remove the variable.
unset($variableName);



Question: What are default session time and path?
Session Time: 1440 seconds
Session Path: /tmp folder in server


Question: What is PEAR?
PHP Extension and Application Repository (PEAR) is a framework and repository for reusable PHP components.


Question: What is MIME?
Full form of MIME is "Multi-purpose Internet Mail Extensions".
It is extension of e-mail protocol helps to exchanges the different kids of data files over the internet.
Data files may be audio, video, images, application programs and ASCII etc.


Question: How to scrape the data from website using CURL?
To scrap the data from website, Website must be public and open for scrapable.
In the blow code, Just update the CURLOPT_URL to which websites data you want to scrap.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.web-technology-experts-notes.in/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
echo $output;



Question: How to upload the file using CURL?
You can upload a file using CURL.
See following points.
1. Uploading file size must be less than allowed file by Server.
2. If file size is heady, May take more time.
3. replace "uploadFile.zip" with file which you want to upload WITH full path.
4. replace "http://localhost/test/index2" with URL where server has given functionality to upload file.
$file_name_with_full_path = realpath('uploadFile.zip');        
       $url = "http://localhost/test/index2";
       $post_data = array(
           "foo" => "bar",
           "upload" => "@".$file_name_with_full_path
       );
       try {
           $ch = curl_init();
           curl_setopt($ch, CURLOPT_URL, $url);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($ch, CURLOPT_POST, 1);
           curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
           $output = curl_exec($ch);
           curl_close($ch);
       } catch (Exception $e) {
           echo $e->getMessage();
           die;
       }



Question: Can I set the header in CURL?
Yes, you can set the header in CURL using CURLOPT_HEADER.
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); 



Question: How can i execute PHP File using Command Line?
For this, you need PHP CLI(Commnd line interface)
Just login to you command line interface.
You have to prepend the "PHP" and need to mention the full-path/relative of file
Execute the file in following way.
php E://wamp/www/project/myfile.php



Question: How can we get the current session id?
echo session_id();

You can also set the session_id using same above function.


Question: What are different type of sorting functions in PHP?
sort() - sort arrays in ascending order. asort() - sort associative arrays in ascending order, according to the value.
ksort() - sort associative arrays in ascending order, according to the key.
arsort() - sort associative arrays in descending order, according to the value.
rsort() - sort arrays in descending order.
krsort() - sort associative arrays in descending order, according to the key.
array_multisort() - sort the multi dimension array.
usort()- Sort the array using user defined function.


Question: How to save the session data into database?
To maintain the session data, we can use session_set_save_handler function.
session_set_save_handler ( 'openFunction' , 'closeFunction', 'readFunction' , 'writeFunction' , 'destroyFunction', 'gcFunction' )

In this function, we provide 6 callback functions which call automatically.
For Example
openFunction will be called automatically when session start.
closeFunction will be called automatically when session end.
readFunction will be called automatically when you read the session.
writeFunction will be called automatically when you write in the session.
destroyFunction will be called automatically when you destroy in the session.
gcFunction will be called automatically when session inactive for long time.







Question: What are different type of errors?
E_ERROR: A fatal error that causes script termination.
E_WARNING: Run-time warning that does not cause script termination.
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code.
E_CORE_ERROR: Fatal errors that occur during PHP's initial startup.
E_CORE_WARNING: Warnings that occur during PHP's initial startup.
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error E_ALL: Catches all errors and warnings

PHP Quick Guide: The Fundamentals

What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. – php.net
PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

Escaping from HTML

Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents.

Will render:

Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ‘[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

String Functions

These functions all manipulate strings in various ways.

You can find a full list of string functions here. Some more specialized sections can be found in the regular expression and URL handling sections.

Numbers

Integers

An integer is a number that can be written without a fractional component.

Floating Point Numbers

The term floating point is derived from the fact that there is no fixed number of digits before and after the decimal point; that is, the decimal point can float.

Array

An array is a data structure that stores one or more type of values in a single value.

Associative Array (Hash or Dictionary)

An associative array is  an array with strings as index.

Array Functions

Here some examples of array functions, for a full list of functions click here.

NULL & empty

NULL

The special NULL value represents a variable with no value. NULL is the only possible value of type null.
A variable is considered to be null if:
  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset().
There is only one value of type null, and that is the case-insensitive constant NULL.
  1. <?php
  2. $var = NULL;
  3. ?>

empty

(PHP 4, PHP 5, PHP 7)
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
Note: Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

Type Juggling and Typecasting

Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

Typecasting

Converting an expression of a given type into another type is known as type-casting.

Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

if , elseif and else Statements

if

(PHP 4, PHP 5, PHP 7)
The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:
  1. if (expr)
  2. statement
The expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE – it’ll ignore it.

else / elseif

(PHP 4, PHP 5, PHP 7)
elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.

Logical Operators

ExampleNameResult
$a and $bAndTRUE if both $a and $b are TRUE.
$a or $bOrTRUE if either $a or $b is TRUE.
$a xor $bXorTRUE if either $a or $b is TRUE, but not both.
! $aNotTRUE if $a is not TRUE.
$a && $bAndTRUE if both $a and $b are TRUE.
$a || $bOrTRUE if either $a or $b is TRUE.
The reason for the two different variations of “and” and “or” operators is that they operate at different precedences. (See Operator Precedence.)

Comparison Operators

equal: ==
identical: ===
compare: > < >= <= <>
not equal: !=
not identical: !==

Switch

(PHP 4, PHP 5, PHP 7)
The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Loops

While

(PHP 4, PHP 5, PHP 7)
while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:
while (expr)
statement
The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won’t even be run once.

For

(PHP 4, PHP 5, PHP 7)
for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3)
statement
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you’d want to end the loop using a conditional break statement instead of using the for truth expression.

Foreach

(PHP 4, PHP 5, PHP 7)
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).
The second form will additionally assign the current element’s key to the $key variable on each iteration.
It is possible to customize object iteration.
Note:
In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Continue & Break

Continue

(PHP 4, PHP 5, PHP 7)
Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
Note: In PHP the switch statement is considered a looping structure for the purposes of continue. continuebehaves like break (when no arguments are passed). If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

Break

(PHP 4, PHP 5, PHP 7)
Break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

Pointers

There’s an internal implementation for “arrays” in PHP “behind the scenes”, written in C. This implementation defines the details of how array data is actually stored in memory, how arrays behave, how they can be accessed etc. Part of this C implementation is an “array pointer”, which simply points to a specific index of the array.

Defining Functions

A function may be defined using syntax such as the following:
  1. <?php
  2. function say_hello_to($name){
  3. return "Hello, {$name}!";
  4. }
  5. ?>
Any valid PHP code may appear inside a function, even other functions and class definitions.
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
Tip
See also the Userland Naming Guide.
Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

Function Arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.
PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported.

Default Argument Values

A function may define C++-style default values.

Returning Values

Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information.
Note: If the return is omitted the value NULL will be returned.
For More information about PHP please read the docs here.

lEARNING: SQL | WHERE Clause

SQL | WHERE Clause WHERE keyword is used for fetching filtered data in a result set. It is used to fetch data accord...