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