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




How to Call async/await functions in parallel

How to Call async/await functions in parallel

Question: How to Call async/await functions in parallel?
We can use await on Promise.all()

Syntax
let [someResult, anotherResult, anotherResult3] = await Promise.all([someCall(), anotherCall(), another3Call()]);


Example
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});



Question: How to read data from Image url and write in file synchronous?
First, We must need to install https and fs module in node.
https - Its for execute the https request.
fs - for save the file in local.

Example
const https = require('https');
const fs = require('fs');

const file = fs.createWriteStream("file.jpg");//Create  a file
const request = https.get("https://img.youtube.com/vi/0yX92mE6h2M/mqdefault.jpg", function(response) {
  response.pipe(file);//Add the image-content in file
});



Question: What is difference between app.listen and server.listen?
Both are used to start the server, for listening the request.

We need server.listen for create the request on https server.
var https = require('https');
var server = https.createServer(app).listen(config.port, function() {
    console.log('Https App started');
});

app.listen will create http server.
var express = require('express');
var app = express();
app.listen(1234);



Question: How to return the json response?
You can use res.json() to return the response in APIs
Example
exports.get_data = function(req, res) {  
    res.json({name: "web technology experts",description:"this is description"});
};



Question: How to auto-reload files in Node.js in Local server?
While doing the development, you do not want to re-start the node server each time, when you made changes.
For this you can use nodemon module.
Install the nodemon module
npm install nodemon -g 

start the node with nodemon instead of node
nodemon app.js



Question: How to create https request?
To Create the https server,
---first you need to install the modules like https, express and socket.io etc
---You need private/public keys for ssl

var https = require('https');
var privateKey  = fs.readFileSync('public/server.key', 'utf8');
var certificate = fs.readFileSync('public/file.crt', 'utf8');
var caCertificate = fs.readFileSync('public/chain.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate, ca: caCertificate};
var httpsServer = https.createServer(credentials, app);  
var io = require('socket.io')(httpsServer);  
httpsServer.listen(443,function() {
    console.log('https listening on 443');
});