Showing posts with label Node Interview Questions and Answers. Show all posts
Showing posts with label Node Interview Questions and Answers. 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, 1 July 2020

Node JS Interview Questions and Answers for 3 Years experience



Question: What is the difference between tilde(~) and caret(^) in package.json?
~ update you to all future patch versions, without incrementing the minor version. ~2.2.3 will use releases from 2.2.3 to 2.3.0.
^ update you to all future minor/patch versions, without incrementing the major version. ^2.3.3 will use releases from 2.3.3 to 3.0.0.



Question: How do I pass command line arguments to a Node.js program?
In Node - How to pass arguent
node process-2.js one two=three four
In Node - How to get argument value
process.argv



Question: How do I update each dependency in package.json to the latest version?
npm i -g npm-check-updates
ncu -u
npm install



Question: How can I update NodeJS and NPM to the next versions?
npm install -g npm



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



Question: How to read environment variables?
var mode   = process.env.NODE_ENV;
var apiKey = process.env.apiKey; 



Question: How to parse JSON using Node.js?
//Parse JSON Data
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
}));



Question: How  an HTTP POST request made?
var request = require('request');
request.post(
    'https://www.example.com',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);



Question: How can I get the full object in Node.js's console.log(), rather than Object?
const util = require('util');
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

OR
console.log(JSON.stringify(myObject, null, 4));




Question: How to encode a text using base64?
Buffer.from("Hello World").toString('base64'); //SGVsbG8gV29ybGQ=


Question: How to decoded a text which is encoded with base64?
Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'); //Hello World


Monday, 4 March 2019

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

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


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

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



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


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


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


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



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


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


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


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



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


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



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


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



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



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



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

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

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

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

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

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


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

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


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



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



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



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


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

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

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



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



Wednesday, 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, 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'); 
});