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

Wednesday, 29 July 2020

How do I manage MongoDB connections in a Node.js web application?

How do I manage MongoDB connections in a Node.js web application?

Question: How do I manage MongoDB connections in a Node.js web application?
You need to install mongoose and bluebird module.
Also you must have mongodb install in server, As you need mongodb URL and port on which mongodb running.

Example
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
//mongodb connection with error handing
mongoose.connect(config.MONGO_DB_URL + config.MONGO_DB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("MongoDB connected Successfully.!");
});




Question: mongoose - find all documents with IDs listed in array?
var AjaxChatUser = mongoose.model('AjaxChatUser');
AjaxChatUser.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});



Question: How to npm install to a specified directory?
Use --prefix option, to installed in specific directory.
Example
npm install --prefix  -g



Question: How to declare multiple module.exports in Node.js?
You can put multiple function inside module.exports.

Example
module.exports = {
    method: function() {},
    otherMethod: function() {},
};


Question: Can we write a JS code that work for both (node and the browser)?
Yes, We can write.
Suppose we have mymodule.js which have following code.
Example of Code
(function(exports){
   exports.test1 = function(){
        return 'this is test1 function.'
    };
   exports.test2 = function(){
        return 'this is test2 function.'
    };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);


In Node (Server side()
var share = require('./mymodule.js');
share.test1();
share.test2();


In Browser (Client side()
//Include the js with script tag
share.test1();
share.test2();




Question: How we can use global variable in Node?
We can use with global.varname
global.version='1022.55';



Question: How we can access static files with express.js in Node?
Use following to set the folder as static so that we can put public files here.
app.use(express.static('public')); //public folder




Wednesday, 22 July 2020

How to determine a user's IP address in node


How to determine a user's IP address in node
Question: How to determine a user's IP address in node?
We can use request.connection.remoteAddress to detect the IP Address in node but sometimes server is running behind the load balancer, In this case we need to check for x-forwarded-for

Example
exports.check_node = function(req, res) {
    var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);
    
    res.json({ip:ip});
};




Question: How can I use wait In Node.js?
You can use setTimeout function similar to javascript

Example
function function1() {    
    console.log('Welcome to My Console,');
}

function function2() {    
    console.log('Console2');
}

setTimeout(function2, 3000); //call second
function1(); //Call first



Question: Command to remove all npm modules in windows?
  1. Remove module local
    Go to directory with name of node_modules under current project. DELETE all the folder.
  2. C:\Users\DELL\AppData\Roaming\npm\node_modules
    Delete all the files



Question: Node.js check if path is file or directory?
For this, you need to install the fs module.
var fs = require('fs');
stat = await fs.lstat(PATH_HERE)
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSocket()



Question: What is use of app.use in express?
app.use is a method to configure the middleware used by Express.


Question: Difference between process.stdout.write and console.log?
console.log() calls process.stdout.write with formatted output.
console.log() explains in library
console.log = function (d) {
  process.stdout.write(d + '\n');
};



Question: How to Detect if file called through require or directly by command line?
if (require.main === module) {
    console.log('called directly');
} else {
    console.log('required as a module');
}



Question: What is the use of next() in express?
It passes control to the next matching route.
For Example:
app.get('/user/:id?', function(req, res, next){
    var id = req.params.id;
    if (id) {
        // do something
    } else {
        next(); 
    }
});




Thursday, 2 July 2020

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

Question: How to write in files synchronous in Node.js?
const fs = require('fs');
fs.writeFileSync('/fold/test.txt', 'Write in file');



Question: What is the difference between --save and --save-dev?
--save-dev is used to save the package for development purpose. Example: unit tests, minification
--save is used to save the package required for the application to run.



Question: is node single threaded or multithreaded?
It is a single threaded language which in background uses multiple threads to execute asynchronous code. Also its is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads.


Question: How to print console without a trailing newline?
    process.stdout.write("hello: ");



Question: How to create a directory if it doesn't exist using Node.js?
var fs = require('fs');
var dir = './tmp';
if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}



Question: How can we execute binary/exe files in Node ?
const { exec } = require('child_process');
exec('wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }
});



Question: Is there a way to get version from package.json?
var pjson = require('./package.json');
console.log(pjson.version);



Question: How can I update npm on Windows?
Simple way
Download and run the latest MSI from nodejs.org. The MSI will update your installed node and npm.


Question: How can node in background?
nohup node server.js &



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



Question: How to get the full url in Express?
var url = require('url');
function fullUrl(req) {
  return url.format({
    protocol: req.protocol,
    host: req.get('host'),
    pathname: req.originalUrl
  });
}




Wednesday, 8 April 2020

Difference between mysql.createConnection and mysql.createPool in Node.js?

Difference between mysql.createConnection and mysql.createPool in Node.js?

mysql.createConnection

When you create a connection with mysql.createConnection, you only have one connection and it lasts until you close it OR connection closed by MySQL.

A single connection is blocking. While executing one query, it cannot execute others. hence, your application will not perform good.
Example:
var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb',
});


mysql.createPool

mysql.createPool is a place where connections get stored.
When you request a connection from a pool,you will receive a connection that is not currently being used, or a new connection.
If you're already at the connection limit, it will wait until a connection is available before it continues.

A pool while one connection is busy running a query, others can be used to execute subsequent queries. Hence, your application will perform good.
Example:
var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb',
});



Sunday, 3 November 2019

Node.js questions and answers for 1 year experience

Node.JS questions and answers for 1 year experience

Question: How to update NPM?
npm install -g npm



Question: How to write in file through NodeJs?
For this, you need to use filesystem API.
var fs = require('fs'); //Create Object
var fileName='/tmp/myfile.txt';
var fileContent='Hello this is text message';
fs.writeFile(fileName, fileContent, function(err) {
    if(err) {
        return console.log('error:'+err);
    }
    console.log("Content saved in File successfully");
}); 



Question: How to check File Exist OR Not?
For this, you need to use filesystem API.
var fs = require('fs');
var fileName='/tmp/myfile.txt';
if (fs.existsSync(fileName)) {
    console.log('File Exist');
}else{
 console.log('File Does not Exist');
}



Question: How to remove a file?
For this, you need to use filesystem API.
var fs = require('fs');
var fileName='/tmp/myfile.txt';
fs.unlinkSync(fileName);



Question: How to read process EVN?
console.log(process.env)
Output
{ 
  ENV_NODE_CONSOLE: 'production',
  DYNO: 'web.1',
  PATH: '/app/vendor/node/bin:/app/bin:/app/node_modules/.bin:bin:node_modules/.bin:/usr/local/bin:/usr/bin:/bin',
  PWD: '/app',
  MONGOLAB_URI: 'mongodb://heroku_app14996339_A:PQrhCoawHlCQcpOQNRkBeEbXLXnhYNSz@ds043987.mongolab.com:43987/heroku_app14996339',
  PS1: '[033[01;34m]',
  NODE_ENV: 'production',
  SHLVL: '1',
  HOME: '/app',
  NO_CLUSTER: 'true',
  PORT: '24118',
  _: '/app/vendor/node/bin/node'
 }



Question: How to retrieve POST query parameters in Express?
app.post('/test-page', function(req, res) {
    console.log(req.body);//here is post data
});



Question: How to encode a sting using base64_encode?
console.log(new Buffer("1").toString('base64')); //MQ==



Question: How to decode a sting using base64_decode?
console.log(new Buffer("MQ==", 'base64').toString('ascii'));//1



Question: How can I pretty-print JSON using node.js?
var testVar ='{ a:1, b:2, c:3 }, null, 4';
JSON.stringify(testVar);



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


Question: How to exit from unix terminal in Node.js?
ctr+c twice




Sunday, 13 October 2019

How to create http server in NodeJS?

How to create http server in NodeJS?

Question: How to create a New server in nodejs?

var http = require("http");
http.createServer(function(request, response) {    
response.writeHead(200, {'Content-Type': 'text/html'});    
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World Page</title>");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
    response.end();
}).listen(8081);



Question: How to Execute above response in browser?
http://127.0.0.1:8081/
You should be already installed WampServer/Xampp Server.


Question: How to install httpdispatcher?
npm install httpdispatcher



Question: Give an example of http GET Request?

dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});



Question: Give an example of http POST Request?

dispatcher.onPOST("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('<h3>
Received POST Data</h3>
');
});



Question: Give an full example of httpdispatcher which have multiple pages?

var dispatcher = require('httpdispatcher'); 
function handleRequest(request, response) {
    try {
        //log the request on console
        console.log(request.url);
        //Disptach
        dispatcher.dispatch(request, response);
    } catch (err) {
        console.log(err);
    }
}
dispatcher.setStatic('resources');

//A sample GET request    
dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});

dispatcher.onGet("/aboutus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
About US Page</h3>
');
});


var http = require('http');
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(8081, function() {
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", 8081);
});




Saturday, 12 October 2019

How to install and Connect to MySQL in NodeJS?

How to install and Connect to MySQL in NodeJS?

Hope you have already installed nodeJS, If not Please install first.
https://nodejs.org/en/download/

Question: How to install new package in nodejs?
npm install packagename



Question: How to install MySQL?
npm install mysql



Question: How to update MySQL?
npm update mysql



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



Question: How to connect to MySQL in nodeJS?
var mysql = require("mysql");
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 connect to MySQL in single string in nodeJS?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/database'); 
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to get records from MySQL database in node.js?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "enterprisedev2"
});

con.query('SELECT * FROM admin_members where id<=10 ', function(err, rows) {
    for (var i = 0; i < rows.length; i++) {
        console.log(rows[i]);
    }
});


Question: How to insert record in database?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/mydb');
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
con.query('INSERT INTO messages set ?', post, function(err, result) {
    if (err) {
        console.log(err.message);
    } else {
        console.log('record added in db');
    }
});



Question: How to print the query while inserting record?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/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);



Question: Given another way to insert data in MySQL Database?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/enterprisedev2');

/* data insert in db */
var postData = {
    userID: "1",
    userName: "arunkg",
    userRole: "1",
    text: 'kkkkkkkkkkkkkkkk',
    status: "1",
    vid: '21'
};

var mysqlProfiler = con.query('INSERT INTO `messages` (`userID`, `userName`, `userRole`,`text`,`status`,`vid`) VALUES (' + [postData.userID, mysql.escape(postData.userName), postData.userRole, mysql.escape(postData.text), postData.status, postData.vid] + ')', function(err, result) {
    if (err) {
        //console.log(err.message);
    } else {
        console.log('record added in db');
    }
});



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



Tuesday, 5 February 2019

Node Js Buffer module examples with script code

Node Js Buffer module examples with script code

Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers. Buffer class is a global class that can be accessed in an application.


Question: How to create an empty buffer object?
var bufferData=Buffer.alloc(1024); //1024 bytes



Question: How to write in buffer object?
var bufferData.write('this is string'); //write only string



Question: How to create an array of buffer?
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
console.log(bufferData);//

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
console.log(arrayObject);



Question: What is concat? How to concate the buffer data?
Concatenates an array of Buffer objects into one Buffer object
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
bufferData=Buffer.concat(bufferData);

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
bufferData=Buffer.alloc(1024);
bufferData = Buffer.concat(arrayObject);
console.log(bufferData);



Question: How to compare two buffer?
var buf1 = Buffer.from('abc');
var buf2 = Buffer.from('abc');
var compare1 = Buffer.compare(buf1, buf2);
console.log(compare1); //0

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var compare2 = Buffer.compare(buf1, buf2);
console.log(compare2); //-1

var buf1 = Buffer.from('b');
var buf2 = Buffer.from('a');
var compare3 = Buffer.compare(buf1, buf2);
console.log(compare3); //1



Question: How to check if data is buffer?
Buffer.isBuffer(obj);//true|false



Thursday, 20 December 2018

Node JS tutorial for beginner

NodeJS Framework Understanding

Question: What is NodeJS
Node.js is a platform built for fast and scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. It can be used in Websites application, Android applicationa and IOS application etc.


Question: What type of framework is Nodejs?
NodeJS is JavaScript-based framework/platform



Question: Is Nodejs Server OR Cient Side?
Both, Node work for both.



Question: What is REPL?
REPL stands for Read Eval Print Loop
Node.js comes with virtual environment called REPL (also Node shell).


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



Question: How to exist from REPL?
ctrl + c twice 



Question: How to install module in NodeJS?
npm install express
for install express.


Question: How to uninstall module in NodeJS?
npm uninstall express
for uninstall express.


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



Tuesday, 18 July 2017

node js underscore tutorial with examples

node js underscore tutorial with examples

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





Question: How to include underscore in nodeJS?
var _ = require('underscore');





Question: What is map in underscore? How to use? Give example?
Produces a new array of values by mapping each value in list through a function. The iterates is passed three arguments: the value, then the index (or key) of the iteration, and reference.


console.log(_.map([1, 2, 3], function(num){ return num * 2; })); //2, 4, 6
console.log(_.map([1, 2, 3], function(num){ return num * 3; })); //3,6,9



Question: Give an example of underscore.each?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: Give an example of underscore.reduce?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: Give an example of underscore.reduce?
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: How to check if variable is empty OR Not?
_.isEmpty({});//true
_.isEmpty({'1'});//false



Question: How to create range values?
_.range(6);//[1,2,3,4,5,6]



Question: Can we use underscore for Web Client?
Yes, for this you need to include following JS.
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js



Question: What are collections available in underscore?
each
map
reduce
reduceRight
find
filter
where
findWhere
reject
every
some
contains
invoke
pluck
max
min
sortBy
groupBy
indexBy
countBy
shuffle
sample
toArray
size
partition



Question: What are array are available in underscore?
first
initial
last
rest
compact
flatten
without
union
intersection
difference
uniq
zip
unzip
object
indexOf
lastIndexOf
sortedIndex
findIndex
findLastIndex
range



Question: What functions are available in underscore?
bind
bindAll
partial
memoize
delay
defer
throttle
debounce
once
after
before
wrap
negate
compose



Thursday, 13 July 2017

Express JS Interview Questions and Answer for 1 Year Experienced

Express JS Interview Questions and Answer for 1 Year Experienced

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: Why I Should Use Express Js?
It is light-weight server side web application framework which work on node.js platform.


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 + req.path;



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



Question: How To enable debugging In Express App?
In windows
set DEBUG=express:* & node index.js

In Linux
DEBUG=express:* node index.js


Question: How to render plain Html?
res.sendFile();
res.render();


Question: How to use handle get request in express Js?
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: How to receive get parameter in Express Js?
app.get('/listing', function (req, res) {   
    console.log(req.query);   //Receive get data
});



Question: How to receive post parameter in express Js?
app.post('/listing', function (req, res) {   
    console.log(req.body);   //Receive post data
});



Question: What is Callback in node.js?
Callback function is used in node.js to deal with multiple requests made to the server. Node is single thread based application and works on the behalf of events.


Question: How to send Ajax call in NodeJS?
Install the request
npm install request

request = require('request');
request( "http://exmaple.com:8081:/users/login/?username=testing@no-spam.ws&password=73278342", function(err, res, body) {                    
          console.log(res.console);          
      });



Question: How to get cookies in expressJs?
npm install cookie-parser
var express = require('express');
var app = express();

var cookieParser = require('cookie-parser');
app.use(cookieParser());

app.get('/listing', function (req, res) {   
    console.log(req.cookies);    
});



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



Question: List out some REPL commands in Node.js?
  1. Ctrl + c - For terminating the current command.
  2. Ctrl + c twice – For terminating REPL.
  3. Ctrl + d - For terminating REPL.
  4. Tab Keys - list of all the current commands.
  5. .break - exit from multiline expression.
  6. .save with filename - save REPL session to a file.



Question: How you can update NPM to new version in Node.js?
sudo npm install npm -g



Question: What do you mean by "Callback hell"?
"Callback hell" is referred to heavily nested callbacks which has become unreadable.


Question: What are "Streams" in Node.JS?
Streams are objects which will let you read the data from source and write data to destination as a continuous process.


Question: What you mean by chaining in Node.JS?
It's a mechanism in which output of one stream will be connected to another stream and thus creating a chain of multiple stream operations.


Question: What is the use of method – spawn()?
This method is used to launch a new process.
child_process.spawn(command[, args][, options])