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