Friday, 10 March 2017

Node js Tutorial for beginners with examples - Page 3

Node js Tutorial for beginners with examples - page 3

Question: How do I pass command line arguments? and how i get the arguments?
Pass argument through Command line
node main.js one two=three four

Script to read value from command line
process.argv.forEach(function (val, index, array) {
  console.log(index + '=> ' + val);
});
Output
0=> node
1=> /data/node/main.js
2=> one
3=> two=three
4=> four



Question: How can we debug Node.js applications?
Install node-inspector
npm install -g node-inspector



Question: How to debug application through node-inspector
node-debug app.js



Question: What is the purpose of Node.js module.exports?
module.exports is the object that's run as the result of a require call.
file: main.js
var sayHello = require('./sayhellotoworld');
sayHello.run(); // "Hello World!"

sayhellotoworld.js
exports.run = function() {
    console.log("Hello World!");
}



Question: How to exit in Node.js?
process.exit();

End with specific code.
process.exit(1);



Question: Read environment variables in Node.js?
process.env.ENV_VARIABLE



Question: How to pars a JSON String?
var str = '{ "name": "Web technology experts notes", "age": 98 }';
var obj = JSON.parse(str);



Question: How to get GET (query string) variables in Node.js? include the "url" module
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
console.log(query);



Question: How to get GET (query string) variables in Express.js?
var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);
});



Question: How to make ajax call in nodeJS?
var request = require('request');
request.post(
    'http://www.example.com/action',
    { json: { name: 'web technology experts',age:'15' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);