Showing posts with label NodeJS. Show all posts
Showing posts with label NodeJS. Show all posts

Monday 20 March 2017

Node js Tutorial for beginners with examples - page 5

Node js Tutorial for beginners with examples - page 5

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'

Friday 17 March 2017

Node js Tutorial for beginners with examples - page 4

Node js Tutorial for beginners with examples - page 4

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



Friday 10 March 2017

Node js Tutorial for beginners with examples - Page 3

Node js Tutorial for beginners with examples - page 3

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)
        }
    }
);



Thursday 9 March 2017

Node js Tutorial for beginners with example - Page 2

Node js Tutorial for beginners with examples - page 2

Question: Does nodeJS support concurrency?
Yes, It support concurrency where as it is single thread application.
It uses event and callbacks to support concurrency.
Node uses observer pattern and thread keeps an event loop and whenever a task gets completed.


Question: What is event driven programming?
Event driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions, sensor outputs, messages from other programs/threads.


Question: How NodeJS starts?
When Node starts its server, it simply initiates all variables, declares functions and then simply waits for the event to occur.


Question: How node use Event-Driven programming?
In an event-driven application, there is a main loop that listens for events, and then triggers a callback function when one of those events is detected.
The functions that listen to events act as Observers, whenever an event gets fired, listener function starts executing.
Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners.


Question: How to read content from text file?
In Node "async function" accepts a callback as the last parameter and a callback function accepts an error as the first parameter.
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});



Question: What is EventEmitter class?
All objects that emit events are instances of the EventEmitter class.
eventEmitter.on() function that allows one or more functions to be attached.
When the EventEmitter emits an event, all functions attached to that event are called synchronously.


Question: Give an exmaple of EventEmitter?
const EventEmitter = require('events');
var eventEmitter = new events.EventEmitter();

//call when emit
eventEmitter.on('event', function(a, b) {
  console.log(a, b, this);  
});
//Email the data
eventEmitter.emit('event', 'a', 'b');



Question: What are common EventEmitter methods?
  1. addListener(event, listener): Add one or more listener to the event.
  2. on(event, listener): Adds a listener at the end of the listeners array for the specified event.
  3. once(event, listener): Adds a one time listener to the event.
  4. removeListener(event, listener): Removes a listener from the listener array for the specified event



Question: How to create buffer in node?
Node provides Buffer class which store raw data similar to an array of integers/string but corresponds to a raw memory allocation.
//Create a buffer
var buf = new Buffer([107, 207, 370, 470, 570]);

//Convert Buffer to JSON
buf.toJSON()

//Print the buffer
console.log(buf.toJSON());

//Concatinate to buffer
var buf1 = new Buffer('Quick Learnig');
var buf2 = Buffer.concat([buf,buf1]);

//Copy buffer
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])

//Slice Buffer
buf.slice([start][, end])

//Buffer Length
buf.length;



Question: What are Streams in NodeJS?
Streams are objects that let you read data from a source OR write data to a destination.


Question: What are different type of Streams?
  1. Readable: used for read.
  2. Writable: used for write.
  3. Duplex: used for read and write.
  4. Transform: type of duplex stream where the output is computed based on input
Each type of Stream(Readable,Writable,Duplex,Transform) is an EventEmitter instance.


Question: What type of events are through by streams(Readable,Writable,Duplex,Transform) ?
data
end
error
finish


Question: Give an example of working streams in NodeJS?
var fs = require("fs");
var textdata = '';
var readerStream = fs.createReadStream('test/inputdata.txt');
// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

readerStream.on('data', function(chunk) {
    textdata += chunk;
});
readerStream.on('end', function() {
    console.log('All data are:'+textdata);
});
readerStream.on('error', function(err) {
    console.log(err.stack);
});

console.log("Program finished.");



Question: What is Piping the Streams?
Piping is a mechanism where we provide the output of one stream as the input to another stream.
means get output data from one stream and to pass to another stream.


Question: What is Chaining the Streams?
Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations.


Question: Give an example of Synchronous and Asynchronous?
Synchronous: In Synchronous, all request execute one by one means it blocks a program during its execution. see example
var fs = require("fs");
// Synchronous reading
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());


Asynchronous: In Asynchronous, one request does not wait for the execution of another request. Basically its good programming. Asynchronous methods take two parameter first is error and second one is data. See example:
var fs = require("fs");
// Asynchronous reading
fs.readFile('input.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});



Question: How to open file in read mode? What are different flags available?
var fs = require("fs");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
  console.log("File opened successfully!");     
});


r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like 'w' but fails if the path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if the the path exists.


Question: How to get current filename OR dirname?
Get Filename
__filename

Get dirname
__dirname



Friday 3 March 2017

Node js tutorial for beginners with examples

node js tutorial for beginners with examples

Question: What is REPL?
It represents a computer environment like a Unix/Linux shell where a command is entered and the system responds with an output.


Question: What is full form of REPL?
Read. Eval. Print. Loop.


Question: How to start REPL?
Type following command and press enter key.
node



Question: How to calculate 2+2 in Node REPL?
Just type 2+2 and press enter key in REPL Mode.


Question: How to see previous result in REPL?
Use Underscore to see the previous results.
_



Question: What we can do in REPL?
  1. Simple Expression
  2. Use Variables
  3. Multiline Expression
  4. Underscore Variable



Question: What are most common REPL Commands?
ctrl + c ? terminate the current command.
ctrl + c twice ? terminate the Node REPL.
ctrl + d ? terminate the REPL.
Up/Down Keys ? see command history.
tab Keys ? list of current commands.
.help ? list of all commands.
.break ? exit from multiline expression.
.clear ? exit from multiline expression.
.save filename ? save the current session to a file.
.load filename ? load file content in Node REPL session.


Question: What is the difference between local and global module in Node.js?
When we Installed a module locally, then we need to use require() to use module.
When we Installed a module globally, then we need't to use require() to use module.


Question: When to use local and global module?
If we are going to run it on the command line, then we must install the module globally.


Question: How to install mysql locally?
npm install mysql



Question: How to install mysql globally?
npm install mysql -g



Question: What is package.json in module?
All npm packages contain a file, usually in the project root, called package.json.
package.json file holds various metadata relevant to the project.
This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies.
It can also contain other metadata like description, version, license and configuration data.


Question: Give the sample of package.json?
{
  "name" : "name of project",
  "description" : "Project description.",
  "homepage" : "http://example.com",
  "keywords" : ["keyword1", "keyword2", "keyword3", "keyword4", "keyword5"],
  "author" : "hellouser ",
  "contributors" : [],
  "dependencies" : [],
  "repository" : {"type": "git", "url": "git://github.com/example/example.git"},
  "main" : "project.js",
  "version" : "1.2.7"
}


Question: Does package.json exist for each module?
Yes, each package contain the package.json.
It exist in root of module.


Question: Does package.json exist for each module?
Yes,
Each module have its own package.json


Question: How to search a new module?
npm search mysql



Question: How to update existing module?
npm update mysql



Question: Can we create a new module and published?
Yes, We can create a new module.
Following are different ways.
  1. Create package.json
  2. Create a new module using "npm init" commond.
  3. Add the user for new module.
  4. Publish the node module using "npm publish"



Question: Give example Blocking vs non-blocking in node.js?
Create a file with "input.txt" with content "Hello I am here.";


Blocking code
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("End of script");

Output
Hello I am here.
End of script

Non-Blocking code
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});
console.log("End of script");
Output
End of script
Hello I am here.


Question: How to install express-session ?
In Browser (client)
npm install express-session



Question: How to include express-session?
In Server(Node)
var session = require('express-session');
app.use(session({secret: 'this is secret key'}));




Monday 27 February 2017

Real Time Chat With Node JS

Real Time Chat With Node JS

Create a /config.js file (For configuration like Database connection and port)
module.exports = {    
    'SERVERPORT': '8080',            
    'WEBADDRESS': 'http://localhost/',
    'LOG_LEVEL': 'INFO',
    'LOG_FILE_PATH': 'my_log.txt',
    
    
    // MySQL Information
    'MYSQL_HOST': 'localhost',
    'MYSQL_USER': 'root',
    'MYSQL_PASSWORD': '',
    'MYSQL_DB': 'enterprisedev2'
}


Create a /app.js file(Here all nodejs code for working the chat)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
config = require('./config.js');
var mysql = require("mysql");     
request = require('request'),
 util = require('./util')        

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/chat.html');
});

// Log any uncaught exceptions
process.on('uncaughtException', function (exception) {
        console.log(exception); // to see your exception details in the console
        fs.appendFile(config['LOG_FILE_PATH'], exception, null);
});


/* Make DB Connection */
var con = mysql.createConnection({
        host     : config['MYSQL_HOST'],
        user     : config['MYSQL_USER'],
        password : config['MYSQL_PASSWORD'],
        database : config['MYSQL_DB']
}); 

//Check the DB Connection status
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to Db');
        return;
    }
});

  
 

io.on('connection', function(socket) {    
    socket.on('chat message', function(msg) {        
        /** Insert into database **/        
        request(config['WEBADDRESS'] + "ajax/add-chat-message/user_id/" + socket.uid + "/tour_id/" + socket.vid+"/text/"+msg, function(err, res, body) {          
          
          io.sockets["in"](socket.room).emit('chat message', msg,socket.username,socket.vid );
      });            
         
    }); 

    socket.on('new user', function(message, callback) {
        //console.log('New User -' + message);
    });

    socket.on('disconnect', function(message) {
        console.log('user disconnected');
    });

    var usernames = {};
    socket.on('adduser', function(username,vid,uid) {
        console.log(uid);
        var roomName='room_'+vid;
        // store the username in the socket session for this client
        socket.username = username;
        socket.vid = vid;
        //user id
        socket.uid = uid;
        // store the room name in the socket session for this client
        socket.room = roomName;
        // add the client's username to the global list
        usernames[username] = username;
        
         socket.join(roomName);
         //socket.emit('chat message',' You have connected to room1','ChatBot'); //to same window
         socket.broadcast.to(roomName).emit('chat message', username + ' has connected to this room','ChatBot'); //For other windows OR console.
    });
    
    socket.on('updateDetails',function(data){
        console.log(data);
    });

});


http.listen(config['SERVERPORT'], function() {
    console.log('listening on *:'+config['SERVERPORT']);
});



Create chat.html (Here all HTML code where chat will dispaly)

    <ul id="messages"></ul>
<form action="">
<input autocomplete="off" id="m" /><button>Send</button>
        </form>
<script src="//cdn.socket.io/socket.io-1.2.0.js"></script>        
        <script src="//code.jquery.com/jquery-1.11.1.js"></script>
        [style]
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font: 13px Helvetica, Arial; }
            form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
            form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
            form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
            #messages { list-style-type: none; margin: 0; padding: 0; }
            #messages li { padding: 5px 10px; }
            #messages li:nth-child(odd) { background: #eee; }
        [/style]
        [script]     
        var getUrlParameter = function getUrlParameter(sParam) {
            var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&amp;'),
                sParameterName,
                i;

            for (i = 0; i &lt; sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        };

            var vid=getUrlParameter('vid');
            var userId=getUrlParameter('uid');
            
            //var socket = io();
            var socket = io.connect('http://localhost:8080'); 
            //socket.emit('adduser', prompt("What's your name?"),vid);
            socket.emit('adduser', 'Username',vid,userId);                        
            //socket.emit('updateDetails', "{name:'arun',address:'Mohali phase 7'}");
            
            $('form').submit(function(req) {
                console.log('posted');
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
                return false;
            });



            socket.on('chat message', function(msg, username) {                    
                $('#messages').append($('
<li>').html('<b>' + username + '</b><i>('+new Date(new Date().getTime()).toLocaleString()+')</i>: ' + msg));

            });
            

            $.get("/ajax/chat?vid="+vid, function(data) {
                    data = JSON.parse(data);
                  //console.log(typeof data);
                $.each(data, function( index, value ) {
                    console.log(value)
                    $('#messages').append($('</li>
<li>').html('<b>' + value.display_name + '</b><i>('+value.dateTime+')</i>: ' + value.text));
                });
                
            });
            /** List default records **/
            </li>

        [/script]



Question: How to RUN?
Open /chat.html in browser



Question: Now install the required module in node.js?
Go to the folder where app.js is exist. Execute following command
npm install express
npm install mysql
npm install log4js
npm install request

Question: Do i need to install socket.io?
Yes, IF not installed please install.

Helpful link to install socket.
http://stackoverflow.com/questions/18990494/how-to-install-node-js-npm-socket-io-and-use-them

Question: How to run node?
node app.js



Wednesday 8 February 2017

Difference between CreateConnection and poolConnection in NodeJS

Difference between CreateConnection and poolConnection in NodeJS


MySQL CreateConnection Example
var mysqlClient = mysql.createConnection({
         host     : 'localhost',
         user     : 'root',
         password : '',
         database : 'mydb'
}); 
mysqlClient.connect();
mysqlClient.query(
'SELECT id,name,email FROM `cmf_users` WHERE id = ' + data.uid, function (error, results, fields) {
    console.log(results);
});


MySQL PoolConnection Example
var mysqlPool = mysql.createPool({
       connectionLimit : 10,
       host     : 'localhost',
       user     : 'root',
       password : '',
       database : 'mydb'
});
mysqlPool.getConnection(function(err, mysqlConn) {
mysqlConn.query(
    'SELECT id,name,email FROM `cmf_users` WHERE id = ' + data.uid, function (error, results, fields) {
    console.log(results);
    }
    )
});

Friday 3 February 2017

How to execute MySQL queries in node.js?

How to execute MySQL queries in node.js?

Question: How to install mysql in nodeJS?
npm install mysql



Question: How to update mysql in nodeJS?
npm update mysql



Question: How to include MySQL in nodeJS?
var mysql = require("mysql");



Question: How to connect to MySQL in nodeJS?
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});



Question: How to handle error while connecting to MySQL in nodeJS?
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to insert record in database with nodeJS?
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: How to print SQL query in nodejs?
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: How to insert record in database - Full Example?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql); //print the query



Question: How to fetch all records in nodeJS?
var uid=1002;
 mysqlConn.query('SELECT * FROM `messages` WHERE id = '+uid , function (error, results, fields) {
    if (results != null && results.length > 0) {
        for each (var results in res) {
            console.log(res);
         }
    }
}



Wednesday 25 January 2017

How to make a node.js application run permanently

How to make a node.js application run permanently

  1. Open putty
  2. Login to ssh with username and password
  3. Go to the folder where node file exist.
  4. Execute following command
  5. nohup node server.js &

    then execute following command
    rm nohup.out

  6. Now you can close the putty


Question: How to check nodeJS running?
top

Just look for "node", If its shown means running.



Question: How to stop/kill the node?
Get the "process id" from terminal and kill the same.
kill PROCESS_ID

OR
killall node



How to search the process using command?
ps -fC node




Monday 17 October 2016

NodeJS Interview Questions and Answers for

NodeJS Interview Questions and Answers

Question: Node.js is best suited for what type of application?
Node.js is best suited for real-time applications like Online games, Collaboration Tools, Chat Rooms etc where Real time data required without Refreshing the page.


Question: Why I should use NodeJS ?
  1. Best for Real Time Application.
  2. Javascript can be run in client side as well as in Server Side.
  3. Easy to Setup.
  4. Its lightweight and Fast.
  5. Well suited for applications that have a lot of concurrent connections.
  6. Free modules available like socket, MySQL etc



Question: Why I should Not use NodeJS ?
  1. It runs Javascript, which has no compile-time type checking.
  2. Nested callback hell.
  3. Dealing with files can be a bit of a pain.
  4. Not good for Blogs and static sites.



Question: How do I pass command line arguments to Node.js?
In Command Line
node test.js one two three four five

How to get data
var args = process.argv.slice(2);
console.log(args);



Question: How do I debug Node.js applications?
For you need to install node-inspector
npm install -g node-inspector



Question: How to list local packages installed?
npm list



Question: How to list global packages installed?
npm list -g



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



Question: How to parse JSON using Node.js??
JSON.parse()



Question: How to get GET (query string) variables?
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);



Friday 14 October 2016

NodeJS Interview Questions and Answers for beginners

NodeJS Interview Questions and Answers for beginners

Question: What is NodeJS?
Node.js is a server-side platform.


Question: On which engine built on NodeJS??
Node.js is is built on Google Chrome's JavaScript Engine(V8).


Question: What type of application can be built using NodeJS?
  1. server-side application
  2. networking applications



Question: On which OS it can be run?
  1. OS X (Mac)
  2. Microsoft Windows
  3. Linux



Question: In what type of application we can use NodeJS?
  1. I/O bound Applications
  2. Data Streaming Applications
  3. Data Intensive Real-time Applications (DIRT)
  4. JSON APIs based Applications
  5. Single Page Applications



Question: What is REPL?
REPL is environment to test/debug the code of nodeJS.
Full form of REPL is Read Eval Print Loop.


Question: What is package.json?
package.json define the properties of a package like name, description, version, author, contributors and dependencies.


Question: Where does exist package.json in package?
It exist in root folder of every package.


Question: How to create an API in nodeJS?
var mysql = require("mysql");
var app = require('express')();
var http = require('http').Server(app);
var con = mysql.createConnection('mysql://arun:arun@localhost/enterprisedev2');

app.get('/get/records', function(req, res) {
    con.query('SELECT id,userName,text FROM users where usertype=3', function(err, rows) {
        res.send(rows);
    });
});



Question: How to escape a string while insert into database?
var mysql = require("mysql");
mysql.escape('userdata');



Monday 14 December 2015

Express Js Interview Questions and Answers

Express Js Interview Questions and Answers


Question: What is Express Js?
Express JS is a framework which helps to develop web and mobile applications. Its works on nodejs plateform. Its sub part of node.js.



What type of web application can built using Express JS?
you can build single-page, multi-page, and hybrid web applications.



Question: What are core features of Express framework?
  1. Allows to set up middlewares to respond to HTTP Requests
  2. Defines a routing table which can works as per HTTP Method and URL.
  3. Dynamically render HTML Pages


Question: Why I should use Express JS?
Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side.



Question: How to install expressjs?
http://expressjs.com/en/starter/installing.html


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

app.get('/', function(req, res){
    /* req have all the values **/  
  res.send('id: ' + req.query.id);  
});
app.listen(3000);



Question: How to get POST a query in Express.js?
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded 
app.use(bodyParser.urlencoded({     // to support URL-encoded 
  extended: true
})); 



Question: How to output pretty html in Express.js?
app.set('view options', { pretty: true }); Question: How to get the full url in Express?
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host  + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;



Question: How to remove debugging from an Express app?
var io = require('socket.io').listen(app, { log: false });
io.set('log level', 1); 



Question: How to to 404 errors?
app.get('*', function(req, res){
  res.send('what???', 404);
});



Question: How to download a file?
app.get('/download', function(req, res){
  var file = __dirname + '/download-folder/file.txt';
  res.download(file); 
});



Question: What is the parameter “next” used for in Express?
app.get('/userdetails/:id?', function(req, res, next){
 });

req and res which represent the request and response objects
nextIt passes control to the next matching route.



Tuesday 30 December 2014

Node Js Interview Questions and Answers for Experienced

Node Js Interview Questions and Answers for Experienced


Question: What is node.js?
Node.js is a software for scalable server-side and networking applications.
Node.js applications are written in JavaScript.
It can be run within the Node.js runtime on Mac OS X, Windows and Linux with no changes.


Question: In which language Node.js is written?
C,C++, javaScript.


Question: Who is creater of Node.js?
Ryan Dahl


Question: What is current stable version of Node.js?
6.6.0 Version / 15 September 2016.


Question: How node.js works?
Node.js works on a V8 environment, it is a virtual machine that utilizes JavaScript as its scripting language.


Question: From where we can download Node.js?
http://nodejs.org/download/


Question: What do you mean by the term I/O?
Input/Output


Question: What does event-driven programming?
In event-driven programming, flow of the program is determined by events.


Question: Where Node.js can be used?
  • Web applications ( especially real-time web apps )
  • Network applications
  • Distributed systems
  • General purpose application



Question: What is Advantage of Node.js?
Following are advantage of Node.js as compare to other web scripting.
  • Faster
  • More concurrency user
  • Asynchronous
  • Least blocks
  • Helps to build scalable network programs


Question: What are two different types of functions in Node.js?
  • Asynchronous
  • Synchronous



Question: What is Callback in node.js?
It is used to handle the multiple request.


Question: What tool and IDE is used for Node.js?

  • Atom
  • Nodeclipse Enide Studio
  • JetBrains WebStorm
  • JetBrains IntelliJ IDEA
  • Microsoft Visual Studio with TypeScript
  • NoFlo – flow-based programming environment integrated with GNOME APIs




Question: How to get Post Data in Node.js?
app.use(express.bodyParser());
app.post('/', function(request, response){
    console.log(request.body.user);
    
}); 


Question: How to make Post request in Node.js?
 var request = require('request');
request.post(
    'http://www.example.com/action',
    { form: { key: 'value' } },
    function (error, response, body) {
    if (!error && response.statusCode == 200) {
    console.log(body)
    }
    }
);


Question: What is callback hell?
Callback hell refers to heavily nested callbacks that have become unreadable



Question: How to handle the "Unhandled exceptions" in Node.js?
It can be caught at the "Process level" by attaching a handler for uncaughtException event.
Example:
process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
});


Question: How to download image from Web?
#Include Important library
var fs = require('fs'),
request = require('request');

#Create a Download Function
var downloadImage = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

Use the function in following way:
downloadImage('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
  console.log('image is downloaded');
});



Question: How to Remove directory which is not empty?
var rimraf = require('rimraf');
rimraf('/some/directory', function () {
 console.log('Directory is removed'); 
});