Showing posts with label NodeJS. Show all posts
Showing posts with label NodeJS. Show all posts

Thursday 8 June 2017

How to Create RESTful APIs in Node Js using Express JS and MongoDB

How to Create RESTful APIs in Node Js using Express JS and MongoDB

Question: What is RESTful APIs?
Full form of REST is Representational State Transfer. It is web standards architecture used to create an API.


Question: What type of request handled by RESTful APIs?
HTTP requests


Question: How to create an API?
  1. Create a folder with name of api in your node project, and  create three folder inside this. i.e controllers, models and routes.
  2. Create 3 empty files in each folder i.e todoListController.js, todoListModel.js and todoListRoutes.js
  3. Now, Folder Structure will be as below:
  4. -api
        --api/controllers/todoListController.js
        --api/models/todoListModel.js
        --api/routes/todoListRoutes.js
  5. Add Following script in each empty file: todoListController.js
    var mongoose = require('mongoose'),
            Task = mongoose.model('Tasks');
    
    /* List all todoList*/
    exports.list_all_tasks = function(req, res) {
        Task.find({}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    /* List all todoList*/
    exports.create_a_task = function(req, res) {
        var saveData = {}
        saveData.name = req.body.name;
        saveData.status = req.body.status;
        var new_task = new Task(saveData);
        new_task.save(function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });    
    };
    
    /* Get a todo list details*/
    exports.read_a_task = function(req, res) {
        Task.findById(req.params.taskId, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    /* UPdate a toto data*/
    exports.update_a_task = function(req, res) {
        Task.findOneAndUpdate(req.params.taskId, req.body, {new : true}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    exports.delete_a_task = function(req, res) {
        Task.remove({
            _id: req.params.taskId
        }, function(err, task) {
            if (err)
                res.send(err);
            res.json({message: 'Task successfully deleted'});
        });
    };


    todoListModel.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var TaskSchema = new Schema({
        name: {
            type: String,
            Required: 'Kindly enter the name of the task'
        },
        Created_date: {
            type: Date,
            default: Date.now
        },
        status: {
            type: [{
                    type: String,
                    enum: ['pending', 'ongoing', 'completed']
                }],
            default: ['ongoing']
        }
    });
    
    module.exports = mongoose.model('Tasks', TaskSchema);
    


    todoListRoutes.js
    module.exports = function(app) {
        var todoList = require('../controllers/todoListController');
    
    
        // todoList Routes
        app.route('/tasks')
                .get(todoList.list_all_tasks)
                .post(todoList.create_a_task);
    
    
        app.route('/tasks/:taskId')
                .get(todoList.read_a_task)
                .post(todoList.update_a_task)
                .delete(todoList.delete_a_task);
    }; 


  6. Create a myapp.js empty file in project folder and add following script code.
    var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000,
    mongoose = require('mongoose'),
    Task = require('./api/models/todoListModel'),
    bodyParser = require('body-parser');
    
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/Tododb');
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    
    var routes = require('./api/routes/todoListRoutes');
    routes(app);
    
    app.listen(port);
    console.log('RESTful API server started: ' + port+' PORT');
    
  7. Now you need install following modules
    npm install express
    npm install mongoose
    npm install body-parser
    
  8. Now run following command, to test the APIs
    node myapp.js
    



Question: Provide Create Task API
URL: http://localhost:3000/tasks
Method: POST
Request Data:
{
"name":"I need to go for walk",
"status":"ongoing"
}



Question: Provide List All records API
URL: http://localhost:3000/tasks
Method: POST
Response Data:
[{"_id":"5937ff6a5fc96f1c1492877f","name":"I will go for walk daily.","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:28:10.608Z"},{"_id":"593803fb5fc96f1c14928782","name":"Get up early in the morning","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:47:39.246Z"}]



Question: Provide Update Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Request Data:
{  
  "name": "I goes on walk daily.", 
}



Question: Provide Get Records:
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Response Data:
{"_id":"5938d8e86d3e500cd8da6a12","name":"Arun kumar Gupta","__v":0,"status":["ongoing"],"Created_date":"2017-06-08T04:56:08.156Z"}



Question: Provide Delete Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: DELETE
Response Data:
{
  "message": "Task successfully deleted"
}



Tuesday 6 June 2017

How to use cookies with expressJS in node.js

How to use cookies with expressJS in node.js

Question: What is cookies in NodeJS?
Cookies is a node.js module for getting and setting HTTP(S) cookies.


Question: How to install cookies?
npm install cookie-parser       



Question: How to setup cookie with expressJS?
var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());
     



Question: What are the feature of cookie?
  1. Lazy: Since cookie verification against multiple keys could be expensive, So cookies are verified lazily.
  2. Secure: All cookies are httponly by default and cookies sent over SSL are secure by default.
  3. Unobtrusive: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format.
  4. Agnostic: This library is optimized for use with Keygrip, but does not require it.



Question: How to set cookies?
app.get('/set-cook', function(req, res) {
       //Set the cookie
      var c_name='cookie_name';        
      res.cookie(c_name, 'cookie value');
      
      //Send Response
      res.send('cookie value');
});
Note above wll work with expressJs only.
Question: How to get cookies?
app.get('/get-cook', function(req, res) {        
    //Get cookie name
      var cookieValue=req.cookies.cookie_name; 

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to delete cookies?
app.get('/delete-cook', function(req, res) {        

    //Delete the cookie
     clearCookie(cookie_name);

      //Send Response
      res.send('Cookie name is '+cookieValue);
});
Note above wll work with expressJs only.



Question: How to set expiration time for cookie?
res.cookie(name , 'value', {expire : new Date() + 600}); //10 minutes

res.cookie(name , 'value', {expire : new Date() + 3600}); //1 hour

res.cookie(name , 'value', {expire : new Date() + 18000}); //5 hour



Question: What are HTTP cookies?
HTTP cookies are small pieces of data that are sent from a website and stored in your browser. With use of cookies we maintain the login and track the user activities. Cookies are very valuable to better user experience. Following are the three main use of cookies.
  1. Session management
  2. Personalization
  3. Track the user activites



Question: Why we must use Cookie-Free Domains for static contents?
Cookies are very useful in website. But while access static contents of website like CSS, image and JS then there is no use of cookie. Means while Browser is accessing the static file, Server should send the static content without use of cookie. It will improve the website performance.



Monday 5 June 2017

Mongoose Tutorial - listing records, Add Record, update record and delete record

mongoose tutorial - listing records, Add Record, update record  and delete record

Question: How to install the mongoose?
npm install mongoose



Question: How to update the mongoose?
npm update mongoose



Question: How to Start the mongoose?
Include the mongoose in the project
var mongoose = require('mongoose');

Make the Db connection with mongodb
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;

Check the Error OR Success on Db Connection
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});  




Question: How to Create Model with mongoose?
Here we have set the two fields only, you can add more if required.
var TodoSchema = mongoose.Schema({
  id: String, //datatype is string
  name: String, //datatype is string          
});       
var Todo = mongoose.model('Todo', TodoSchema);

In mongoose.model, the first argument is the singular name of the collection.
Mongoose automatically looks for the plural version with lowercase of your model name.
means for Todo, it will look todos.



Question: How to set unique key for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});



Question: How to set unique key and required for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true }, 
  email: { type: String, unique: true, required:true }, 
  name: String, //datatype is string          
});



Question: How to list the records from mongodb?
var cursor = Todo.find({ }).cursor();
cursor.on('data', function(doc) {
    jsonData[doc.id] = doc.name;  
});
cursor.on('close', function() {
    console.log(jsonData);                   
});



Question: How to save the record?
var TodoDetails = new Todo({ id: "10",name:"this id test message"});
TodoDetails.save(function (err) {if (err) console.log ('Error on save!')});        



Question: How to update the record?
 Todo.update({id: "10" }, { $set: { name: "this is update message" }}, {}, function(){
             console.log("Update the records successfully");
        })



Question: How to delete the record?
    Todo.find({ id:"10" }).remove( function(){
     console.log("Record deleted successfully");
    }); 



Question: How to delete the document and check is it deleted?
Todo.find({ id:"10" }).remove( function(err, effectedRows){
    if(err){
         console.log("Unable to delete the record");
    }
    if(effectedRows.n==0){
        console.log("Zero Record deleted");
    }else{
        console.log("Record deleted successfully");
    }
     
 }); 



Question: What are the difference between mongoose.model and mongoose.Schema?
Model is an object that gives you easy access to a collection, allowing you to query the collection and use the Schema to validate any documents you save to that collection. It is created by combining a Schema, a Connection, and a collection name.

Schema is an object that defines the structure of the documents that will be stored.
it enables you to define types and validators for all data.



Question: How to get first record(s) from listing?
Todo.findOne({ 'name': 'kumar' }, 'id', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          

})        



Question: How to fetch specific column?
  Todo.find({ 'name': 'kumar' }, 'id name', function (err, person) {
          if (err) return handleError(err);
            //console.log(person);          
             res.send(person);
        })



Question: How to limit the number of records?
You can use limit method.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3);



Question: How to get listing by name in ascending order?
You can use sort method, -1 means descending order, 1 means ascending order.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: How to use "in" in where clause?
Todo.find({ name: { $in: ['arun', 'gupta']}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: Give full Query example?
Todo.find({ 
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    name: { $in: ['technology', 'web'] }

}, 'id name', function (err, person) {
  if (err) return handleError(err);
    //Here will be display all the records
    console.log(person);               
}).limit(3).sort({ name: -1 });




Question: How to create custom function in mongoose.model?
In schema/Model file (Create a custom function)
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});
TodoSchema.statics.findByIdTest = function (todoId,cb) {
  return this.model('Todo').find({ id: todoId }, cb);
};

How to use controller file.
Todo.findByIdTest(2677,function(error, data){
    console.log(data);    
});




Tuesday 30 May 2017

What is mongoose? How to use mongoose with nodejs for mongodb?

What is mongoose? How to use mongoose with nodejs for mongodb?
 How to use mongoose with nodejs for mongodb?

Question: What is mongoose in node js?
mongoose is an object modeling package for Node that essentially works like an ORM.


Question: How to install mongoose in node js?
npm install mongoose



Question: What is the --save option for npm install?
When we do "npm install", then it install the modules.
If we need to update the version of module in package.json, then we have to do it manually.
BUT when we do "npm install --save", then it install the modules and update the package.json automatically.


Question: What is difference between dependencies and devDependencies?
dependencies are modules your project depends on, devDependencies are modules you use to develop your project.

Examples of dependencies are request, through2 and concat-stream.
Examples of devDependencies are grunt, mocha, eslint, tape, and browserify.


Question: How to connect to MongoDB database?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mongodb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});


Question: How to define the Schema in mongoose?
var userSchema = mongoose.Schema({
  name: String, //datatype is string
  username: { type: String, required: true, unique: true }, //type is string and its required field and its unique
  password: { type: String, required: true },
  admin: Boolean,
  location: String,  
  created_at: Date //datatype of date  
});



Question: How to compile the Schema with model?
var User = mongoose.model('User', userSchema);
module.exports = User;
Here User inside "mongoose.model" is a User model, where all the data will be managed.
var User is an Model Object which will be used to process on the document.



Question: What are different type of data types in mongodb?
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array


Question: How to add a record in document with model?
var userDetails = new User({ name: 'Test user',username:'testuser',password:'test12@',location:'mohali' });
userDetails.save(function (err) {if (err) console.log ('Error on save!')});
console.log(userDetails); 



Question: How to add a record in document with model with FULL CODE?
//include the js
var mongoose = require('mongoose');

//database connection
mongoose.connect('mongodb://localhost:27017/mongodb');

//Create schema
var userSchema = mongoose.Schema({
  name: String, //datatype is string
  username: { type: String, required: true, unique: true }, //type is string and its required field and its unique
  password: { type: String, required: true },
  admin: Boolean,
  location: String,  
  created_at: Date //datatype of date  
});

//create User Object
var User = mongoose.model('User', userSchema);

//Save User details in database
var userDetails = new User({ name: 'Test user',username:'testuser',password:'test12@',location:'mohali' });
userDetails.save(function (err) {if (err) console.log ('Error on save!')});
console.log(userDetails);



Question: How to fetch all records?
User.find({}, function(err, users) {
  if (err) {throw err;}
  console.log(users);
});



Question: How to fetch one record?
User.find({ username: 'testuser' }, function(err, user) {
  if (err) throw err;

  // object of the user
  console.log(user);
});



Question: How to update record?
        User.update({username: 'testuser' }, { $set: { name: "New name" }}, {}, function(){
            //here comes after update the record
        })



Question: How to delete record?
  User.find({ username: 'testuser'  }).remove( function(){
  //write here your code after delete
 }); 



Monday 29 May 2017

Angularjs 2 Interview Questions and Answers

Angularjs 2 Interview Questions and Answers


Question: Why AngualrJS2 over AngualrJS1?
  1. Angular 2 is simpler and faster than Angular 1.
  2. You can update the large data sets with minimal memory overhead.
  3. It will speed up the initial load through server side rendering.



Question: What are the feature of AngualrJS2?
  1. Angular 2 is faster than Angular 1
  2. Angular 2 is easier than Angular 1
  3. It supports old browsers also including IE9+ and Android 4.1+.
  4. It is a cross platform framework.
  5. Angular 2 is mainly focused on mobile apps.
  6. Code structure is very simplified than the previous.



Question: How to install AngualrJS2 in NodeJS?
  1. Create an folder and go inside that folder using command line.
  2. Create en empty file package.json and add following contents.
    {
      "name": "angular2-demo",
      "version": "1.0.0",
      "scripts": {
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "lite": "lite-server",
        "typings": "typings",
        "postinstall": "typings install"
      },
      "license": "ISC",
      "dependencies": {
        "angular2": "2.0.0-beta.7",
        "systemjs": "0.19.22",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.2",
        "zone.js": "0.5.15"
      },
      "devDependencies": {
        "concurrently": "^2.0.0",
        "lite-server": "^2.1.0",
        "typescript": "^1.7.5",
        "typings":"^0.6.8"
      }
    }
  3. Create an empty file tsconfig.json and add following contents.
    {
      "compilerOptions": {
        "target": "es5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      },
      "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
      ]
    }
  4. Create an empty file typings.json and add following contents.
    {
      "globalDependencies": {
        "core-js": "registry:dt/core-js",
        "jasmine": "registry:dt/jasmine",
        "node": "registry:dt/node"
      }
    }
  5. Execute following command from command line.
    npm install

Monday 24 April 2017

Node.js - Global Objects

Node.js - Global Objects

Question: How to display the current filename?
console.log(__filename);
This gives you local filename of the current module.



Question: How to display the current directory name?
console.log(__dirname);
This gives you local dirname of the current module.



Question: How to call a function after 5 seconds?
For this, you can use a global function i.e setTimeout.
function helloFunction(){
   console.log( "Hello, World!");
}
/* helloFunction will call after 5 seconds*/
setTimeout(helloFunction, 5000);



Question: How to stop calling a function which was started with setTimeout?
For this, you can use a global function i.e clearTimeout.
function helloFunction(){
   console.log( "Hello, World!");
}
/* helloFunction will call after 5 seconds*/
var funcObj=setTimeout(helloFunction, 5000);

//stop funtion
clearTimeout(funcObj);



Question: How to call a function in every 7 seconds?
For this, you can use a global function i.e setInterval.
function helloFunction(){
   console.log( "Hello, World!");
}
/* helloFunction will call in every 7 seconds*/
setInterval(helloFunction, 7000);



Question: How to stop calling a function which was started with setInterval?
For this, you can use a global function i.e clearInterval
clearInterval(funcObj);



Question: What are different Console Methods to print info, error, warning etc?
  1. console.log: Prints to stdout with newline.
  2. console.error: Prints to stderr with newline.
  3. console.dir: Uses util.inspect on obj and prints resulting string to stdout.
  4. console.time: Mark the time
  5. console.timeEnd: Mark the time end
  6. console.trace: Print to stderr Trace



Question: What are Process Events?
The process object is a global object and can be accessed from anywhere.
process.on('exit', function(code) {   
   console.log('About to exit with code:', code);
});
console.log("Program Ended");



Question: What are different the Process Events?
  1. exit
  2. beforeExit
  3. uncaughtException
  4. Signal Events


Wednesday 22 March 2017

Express js Interview questions and answers

Express js Interview questions and answers

Question: How to install express js in node?
use following command to install express js.
npm install express



Question: How to use express js in node?
use require to include express module.
var app = require('express')();



Question: How to use handle get request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (req, res) {
   console.log("Got a GET request for the homepage"); //Shown in console
   res.send('This is GET Method for Homepage'); //Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle post request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.post('/user_list', function (req, res) {
   console.log("Got a POST request for the user_list URL"); //Shown in console
   res.send('This is POST Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET/POST request for same URL expressJs?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

//This is POST Request
app.post('/add_user', function (req, res) {
   console.log("Got a POST request for the add_user URL"); //Shown in console
   res.send('This is POST Method for add_user URL');//Display as response
})

//This is Get Request
app.get('/user_list', function (req, res) {
   console.log("Got a GET request for the user_list URL"); //Shown in console
   res.send('This is GET Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET request for all URL start with ab* ?
app.get('/ab*', function(req, res) {   
   console.log("Got a GET request for /ab*");
   res.send('Page Regex Match');
})
Question: How to send Server call in Node?
Install the "request" module with following command.
npm install request

Include the request module in page, and send the request to server.
request = require('request');
request( "http://exmaple.com:8081:/users/add/?n=test&p=2277585&email=test@gmail.com", function(err, res, body) {                    
          console.log(res);
          console.log(body);
      });




Question: How to post data and get in express Js?
HTML Code

<form action="http://example.com:8081/register" method="GET">
Name: <input name="name" type="text" />  <br />
Email: <input name="email" type="text" />
         Phone: <input name="phone" type="text" />
         <input type="submit" value="Submit" />
      </form>


Express JS Code
app.get('/register', function (req, res) {   
   response = {
      name:req.query.name,
      email:req.query.email
      phone:req.query.phone
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



Question: How to get cookie in Express js?
Install the "cookie-parser" module with following command.
npm install cookie-parser

Include the cookie-parser, in node.
app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})


Question: How Static Files works in Express js?
Static files are images/videos/css/js etc.
For this, first you need to set the folder path using "express.static" method. See Example
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
   res.send('Hello ');
});
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
})



Question: How to upload images in Express js?
HTML Code

<form action="http://example.com:8081/file_upload" enctype="multipart/form-data" method="POST">
<input name="file" size="50" type="file" />         
         <input type="submit" value="Submit" />
      </form>

ExpressJS Code
var fs = require("fs");
var express = require('express');
var app = express();
var fs = require("fs");

app.post('/file_upload', function (req, res) {
   console.log(req.files.file.name);   
   var destinationFile = __dirname + "/images/" + req.files.file.name;
   
   fs.readFile( req.files.file.path, function (err, data) {
      fs.writeFile(destinationFile, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully in '+destinationFile,
                  filename:req.files.file.name
               };
            }
         //console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete



Question: How to setup the images and access them?
Add Following code in my server.js (OR main file).
app.use(express.static('public'))
Now, you can add images in public folder and can access like below:
http://localhost:3000/1.jpg
http://localhost:3000/2.jpg
http://localhost:3000/3.jpg



Question: How to do increment the value by 1?
 User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();



Question: How to do decrement the value by 1?
 User.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();




Monday 20 March 2017

Node js Tutorial for beginners with examples - page 5

Node js Tutorial for beginners with examples - page 5

Question: How to check if path is file or directory?
var fs = require("fs");
console.log(fs.lstatSync('/file').isDirectory()); //true/false

Other useful commands
fs.lstatSync('/file').isFile();
stats.isDirectory().isBlockDevice();
stats.isDirectory().isCharacterDevice();
stats.isDirectory().isSymbolicLink() (only valid with fs.lstat());
stats.isDirectory().isFIFO();
stats.isDirectory().isSocket();



Question: How to create a new directory? If does not exist.
var fs = require('fs');
var dir = '/log_folder';

if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

Question: How do I URl Encode in Node.js?
for this, you can use encodeURIComponent (JS function)
encodeURIComponent('select * from table where i()')



Question: How do POST data in an Express JS?
for this, you must install express using "npm install express"
var express = require('express') , app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(request, response){
  console.log(request.body);      
  response.send(request.body);    
});
app.listen(3008);




Question: How to output pretty html in Express?
for this, you must install express using "npm install express"
app.set('view options', { pretty: true });



Question: How to setup cron in NodeJS?
https://github.com/kelektiv/node-cron



Question: How to setup Logging in NodeJS?
  1. Install log4js
    npm install log4js
    
  2. Configuraiton ./config/log4js.json)
    {"appenders": [
        {
            "type": "console",
            "layout": {
                "type": "pattern",
                "pattern": "%m"
            },
            "category": "app"
        },{
            "category": "test-file-appender",
            "type": "file",
            "filename": "log_file.log",
            "maxLogSize": 10240,
            "backups": 3,
            "layout": {
                "type": "pattern",
                "pattern": "%d{dd/MM hh:mm} %-5p %m"
            }
        }
    ],
    "replaceConsole": true }
  3. Log data
    var log4js = require( "log4js" );
    log4js.configure( "./config/log4js.json" );
    var logger = log4js.getLogger( "test-file-appender" );
    logger.debug("Hello");//debug 
    logger.info("Info logs"); //info
    logger.error("Error logs") //error
    

Question: How redis works with NodeJS?
for this, you must install Redis
npm install redis

Include redis in code
redis = require('redis');

Create Redis object
var clientRedis = redis.createClient('6379', '127.0.0.1');

Save the data in Redis
clientRedis.hset("users", '10', 'roberts');  //Name, key, value

Delete the data from redis
clientRedis.del("users", 10);



Question: How to get current date in Nodejs?
new Date().toISOString();// '2016-11-04T14:51:06.157Z'

Friday 17 March 2017

Node js Tutorial for beginners with examples - page 4

Node js Tutorial for beginners with examples - page 4

Question: How to print a stack trace in Node.js?
console.trace("print me")



Question: How can I get the full object in Node.js's console.log()?
const util = require('util');
console.log(util.inspect(myObject, false, null))



Question: How to use jQuery with Node.js?
First instal the jquery then use as following.
require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});



Question: How to change bower's default components folder?
Create a .bowerrc file in root and add following code.
{
  "directory" : "public/components"
}



Question: How to encode base64 in nodeJS?
console.log(new Buffer("hello").toString('base64')); //aGVsbG8=



Question: How to decode base64 in nodeJS?
console.log(new Buffer("aGVsbG8=", 'base64').toString('ascii')); //hello



Question: How to get listing of files in folder?
const testFolder = './files/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
})



Question: How do you extract POST data in Node.js?
app.use(express.bodyParser());
app.post('/', function(request, response){
    console.log(request.body.user.fname);  //print first name
    console.log(request.body.user.lname); //print last name
});



Question: How to remove file nodeJS?
var fs = require('fs');
var filePath = '/folder/arun.docx'; 
fs.unlinkSync(filePath);



Question: How to access the GET parameters after ? in Express?
var email = req.param('email');


Question: How to copy file in nodeJS?
var fs = require('fs');
fs.createReadStream('existing.txt').pipe(fs.createWriteStream('new_existing.txt'));



Question: How to append string in File?
var fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {

});



Question: How to get version of package?
var packageJSON = require('./package.json');
console.log(packageJSON.version);



Question: What is express js?
Express.js is a NodeJS framework.
It is designed for building single-page, multi-page, and hybrid web applications.


Question: How to Send emails in Node.js?
You can use node-email-templates.
https://github.com/crocodilejs/node-email-templates


Question: How to get Ip Address of client?
request.connection.remoteAddress



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



Thursday 9 March 2017

Node js Tutorial for beginners with example - Page 2

Node js Tutorial for beginners with examples - page 2

Question: Does nodeJS support concurrency?
Yes, It support concurrency where as it is single thread application.
It uses event and callbacks to support concurrency.
Node uses observer pattern and thread keeps an event loop and whenever a task gets completed.


Question: What is event driven programming?
Event driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions, sensor outputs, messages from other programs/threads.


Question: How NodeJS starts?
When Node starts its server, it simply initiates all variables, declares functions and then simply waits for the event to occur.


Question: How node use Event-Driven programming?
In an event-driven application, there is a main loop that listens for events, and then triggers a callback function when one of those events is detected.
The functions that listen to events act as Observers, whenever an event gets fired, listener function starts executing.
Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners.


Question: How to read content from text file?
In Node "async function" accepts a callback as the last parameter and a callback function accepts an error as the first parameter.
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});



Question: What is EventEmitter class?
All objects that emit events are instances of the EventEmitter class.
eventEmitter.on() function that allows one or more functions to be attached.
When the EventEmitter emits an event, all functions attached to that event are called synchronously.


Question: Give an exmaple of EventEmitter?
const EventEmitter = require('events');
var eventEmitter = new events.EventEmitter();

//call when emit
eventEmitter.on('event', function(a, b) {
  console.log(a, b, this);  
});
//Email the data
eventEmitter.emit('event', 'a', 'b');



Question: What are common EventEmitter methods?
  1. addListener(event, listener): Add one or more listener to the event.
  2. on(event, listener): Adds a listener at the end of the listeners array for the specified event.
  3. once(event, listener): Adds a one time listener to the event.
  4. removeListener(event, listener): Removes a listener from the listener array for the specified event



Question: How to create buffer in node?
Node provides Buffer class which store raw data similar to an array of integers/string but corresponds to a raw memory allocation.
//Create a buffer
var buf = new Buffer([107, 207, 370, 470, 570]);

//Convert Buffer to JSON
buf.toJSON()

//Print the buffer
console.log(buf.toJSON());

//Concatinate to buffer
var buf1 = new Buffer('Quick Learnig');
var buf2 = Buffer.concat([buf,buf1]);

//Copy buffer
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])

//Slice Buffer
buf.slice([start][, end])

//Buffer Length
buf.length;



Question: What are Streams in NodeJS?
Streams are objects that let you read data from a source OR write data to a destination.


Question: What are different type of Streams?
  1. Readable: used for read.
  2. Writable: used for write.
  3. Duplex: used for read and write.
  4. Transform: type of duplex stream where the output is computed based on input
Each type of Stream(Readable,Writable,Duplex,Transform) is an EventEmitter instance.


Question: What type of events are through by streams(Readable,Writable,Duplex,Transform) ?
data
end
error
finish


Question: Give an example of working streams in NodeJS?
var fs = require("fs");
var textdata = '';
var readerStream = fs.createReadStream('test/inputdata.txt');
// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

readerStream.on('data', function(chunk) {
    textdata += chunk;
});
readerStream.on('end', function() {
    console.log('All data are:'+textdata);
});
readerStream.on('error', function(err) {
    console.log(err.stack);
});

console.log("Program finished.");



Question: What is Piping the Streams?
Piping is a mechanism where we provide the output of one stream as the input to another stream.
means get output data from one stream and to pass to another stream.


Question: What is Chaining the Streams?
Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations.


Question: Give an example of Synchronous and Asynchronous?
Synchronous: In Synchronous, all request execute one by one means it blocks a program during its execution. see example
var fs = require("fs");
// Synchronous reading
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());


Asynchronous: In Asynchronous, one request does not wait for the execution of another request. Basically its good programming. Asynchronous methods take two parameter first is error and second one is data. See example:
var fs = require("fs");
// Asynchronous reading
fs.readFile('input.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});



Question: How to open file in read mode? What are different flags available?
var fs = require("fs");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
  console.log("File opened successfully!");     
});


r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like 'w' but fails if the path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if the the path exists.


Question: How to get current filename OR dirname?
Get Filename
__filename

Get dirname
__dirname