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