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

Friday 19 October 2018

What is NodeJS API wrapper?

What is NodeJS API wrapper?

Question: What is NodeJS API wrapper?
It is RESTful services which is integrated within NodeJS.
With use the these RESTful services, we can integrate third party modules in our nodeJS application.


Question: How can use NodeJS API wrapper in our application?
Just download the source code using npm command and use it.

For Example
npm install --save google



Question: Give Few Examples of NodeJS API wrapper?
Following are few examples which provide API Wrapper to use them:
  1. Braintree provide API so that we can integrate paypment stuff, In NodeJS application.
    https://www.npmjs.com/package/braintree

    Offical Website: https://developers.braintreepayments.com
    API Wrapper Purpose: Integrate braintree in nodeJS application
  2. Ipinfodb provide API so that we can get client detail using Ip Address, In NodeJS applicaton.
    https://www.npmjs.com/package/node-ipinfodb
    Offical Website: http://www.ipinfodb.com/
    API Wrapper Purpose: Get client details like city, state, address, and zip etc using Ip Address.
  3. Google provide API wrapper to get search results from google.com
    https://www.npmjs.com/package/google
    Offical Website: https://gooogle.com
    API Wrapper Purpose: Get search Results from google.com

Question: From where we can find all NodeJS Wrappers?
https://www.npmjs.com/browse/keyword/wrapper




Wednesday 16 May 2018

Node Js Interview Questions and answer for 2 year experienced

Node Js Interview Questions and answer for 2 year experienced

Question: What is JSON.stringify()?
JSON.stringify() method converts a JavaScript object to a JSON string.
Following are three parameter of JSON.stringify.


Value (required): The value to convert to a JSON string.
replacer (optional): A function that alters the behavior of the stringification process, or an array of String and Number objects.
space (optional): A String or Number object that's used to insert white space into the output JSON string for readability purposes.



Question: Give example of JSON.stringify()?
JSON.stringify({});                    // '{}'
JSON.stringify(true);                  // 'true'
JSON.stringify('foo');                 // '"foo"'
JSON.stringify([1, 'false', false]);   // '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
JSON.stringify({ x: 5 });              // '{"x":5}'



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


Question: What is arrow function?
An arrow function expression has a shorter syntax than a regarular function and does not have its own this, arguments, super, or new.target.


Question: Give example of arrow function?
var materials = [
  'Hydrogen',
  'Helium',
  'Beryllium'
];
console.log(materials.map(material => material.length));// expected output: Array [8, 6, 9]


Question: What is Handlebars view engine in nodejs?
Handlebars.js is templating engine in NodeJS. We give the data from node and same used in the handlebar template.



Question: How to configure handlebar?
const hbs = require('hbs');
app.set('view engine', 'hbs');

Now you can place the html files in view folder with extension of .hbs



Question: How to pass the data to handlebar engine and used in view file?
Pass parameter
app.get('/aboutus', (req, res) => {
  res.render('home.hbs', {
    pageTitle: 'About Page Title',
    welcomeMessage: 'Welcome'
  });
});

aboutus.hbs (Use with variable name enclosed with double curly braces)
{{pageTitle}} //About Page Title
{{welcomeMessage}} //Welcome



Question: How to create element(partial) file in handlerbar ?
In node server file, set the following
hbs.registerPartials(__dirname + '/views/partials');

You can call a comman file from another file with following system
{{> header}}

Here header file path is /views/partials/header.hbs


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.
fs.readFile(filePath, function(err, data) {  
  if (err) {
    // handle the error, the return is important here
    // so execution stops here
    return console.log(err)
  }
  // use the data object
  console.log(data)
})



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's a stub? Name a use case?
Stubs are functions that simulate the behaviors of components/modules.
Stubs provide canned answers to function calls made during test cases.
var fs = require('fs')

var writeFileStub = sinon.stub(fs, 'writeFile', function (path, data, cb) {  
  return cb(null)
})

expect(writeFileStub).to.be.called
writeFileStub.restore();



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 REPL Read Eval print Loop.
The REPL in Node.js is used to execute ad-hoc Javascript statements.



Question: Name the types of API functions in Node.js?
Blocking functions In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously.

Non-Blocking functions
In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted.


Question: Explain chaining in Node.js?
Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.


Question: How to get the node version?
node -v



Question: How to access the GET parameters after ? in Express?
URL: /?name=myname&age=32&gender=m
req.query.name;//myname

req.query.age;//32

req.query.gender; //m



Question: What is the difference between __dirname and ./ in node.js?
__dirname is always the directory in which the currently executing script.
. gives you the directory from which you ran the node command in your terminal window


Friday 22 September 2017

Nodejs Interview Questions and Answer 1 year Experience

Nodejs Interview Questions and Answer 1 year Expereince

Question: How do I include a JavaScript file in another file?

Suppose you have following file with hello.js which you want to include.
export function hello() {
  return "Hello, How are you?";
}

Use following syntax to include hello.js?
const helloFileObj = require('./hello');
console.log(helloFileObj.hello()); //It would print Hello, How are you?



Question: What's the difference between tilde(~) and caret(^) in package.json?

the tilde(~) matches the most recent minor version.
For Example ~1.4.3 will match all 1.4.x versions but will miss 1.5.0.
Benefits: Gives you bug fix releases.

the caret(^) matches the most recent major version.
For Example ^1.4.3 will match all 1.x.x versions including 1.5.0 but will hold off on 2.0.0
Benefits: Gives you bug fixes including new functionalities.



Question: How do I pass command line arguments?
node server.js one two=222 three
Here one, two=222 and three are command line arguments (1,2,3 respectively).

Following are way to access argument process.argv is array containing the command line arguments
Following are the output when we print process.argv
Script to print the arguments


Output
0: node
1: server.js
2: one
3: two=222
4: three



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



Question: How to list the packages?
List Local packages?
npm list

List Global packages?
npm list -g

Question: How to exit from node Code?
process.exit()



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



Question: How to generate Secure random token Node.js?
For this you can use crypto module in nodeJS.
require('crypto').randomBytes(48, function(err, buffer) {
  var token = buffer.toString('hex');
});



Question: How to output pretty html in Express?
app.locals.pretty = true;



Question: How to clean node_modules folder of packages that are not in package.json?
app.locals.pretty = true;



Question: How to format a date string in UTC Format?
  
new Date().toISOString(); //2017-09-04T14:51:06.157Z

  
new Date().toISOString().
  replace(/T/, ' ').      // replace T 
  replace(/\..+/, ''); //2017-09-04 14:55:45 



Question: How to get client IP Address in Node JS?
  
app.get(/save-data, function (req, res){
    var ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;   
    console.log(ipAddress); //will print the ip address of client
});



Question: How to force strict mode in node?
Write below code at the top of node file with enclosed with double quote.
 
use strict;


Question: What is promises in node js?
We use the promises for asynchronous operation and it have following 3 states.
  1. Pending
  2. Resolved
  3. Rejected



Question: What is promises in node js?
var somePromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Operation completed');
    // reject(Operation Failed');
  }, 2500);
});

somePromise.then((message) => {
  console.log('Success: ', message);
}, (errorMessage) => {
  console.log('Error: ', errorMessage);
});


Promise contain two parameter i.e. resolve(for success), reject(for failed).


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


Question: How to install Yargs module in node?
npm i yargs --save


Question: Give example of Yargs module?
const argv = require('yargs').argv
console.log(argv.name);//Arun
console.log(argv.age);//28
console.log(argv.city);//Chandigarh

How to pass arguments
node test.js --name="Arun" --age="28" --city="Chandigarh"




Tuesday 12 September 2017

How to create an HTTPS server in Node.js?

How to create an HTTPS server in Node.js?

Question: Run Node with http?
var express = require('express');
var app = express();

//Include modules
var http = require('http').Server(app);
var io = require('socket.io')(http);


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

You can run as http://localhost:8082


Question: What certificate you require for https?
  1. server.key
  2. server.crt
  3. Create a folder public/cert at root of your project and add above 2 files.



Question: Run Node with https?
var express = require('express');
var app = express();

//Include modules

var https = require('https');
fs = require('fs');


var privateKey = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
var io = require('socket.io')(httpsServer);

httpsServer.listen('8083', function() {
    console.log('https listening on *:8083');
});
 

You can run as https://localhost:8083



Tuesday 8 August 2017

Send Acknowledgment for socket.io event

Send Acknowledgment for socket.io event

Question: How to send Acknowledgment for socket.io event?
in node.js (Server side)
io.sockets.on('connection', function(socket){    

    /* Message Received from Client*/
    socket.on('chat_messsage', function(data, callback){        
        var responseData = { 'message':data.message, 'received':1};        
        callback(responseData); //Send Acknowledgment to the client
    });


});

Client Side JavaScript
var socket = io.connect('http://localhost:3000');
socket.on('connected', function (data) {    
    
    //Send message to Server with callback function
    socket.emit('chat_messsage', {message:"this is message"}, function(response){
        console.log(response); //console the Acknowledgment
    });

});



Question: How to Send additional data on socket connection?
Client side, connect with parameter
  var socket =  io.connect(chatURL,{ query: "req_from=browser" });


Sever side, Detect the client Connection.
io.on('connection', function (socket) {
  console.log(socket.handshake.query['req_from']);
});


Question: How to connect node with http and https?
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('cert/server.key', 'utf8');
var certificate = fs.readFileSync('cert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

//http connect
httpServer.listen(8080);
//https connect
httpsServer.listen(8443);