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

Sunday 13 October 2019

How to create http server in NodeJS?

How to create http server in NodeJS?

Question: How to create a New server in nodejs?

var http = require("http");
http.createServer(function(request, response) {    
response.writeHead(200, {'Content-Type': 'text/html'});    
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World Page</title>");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
    response.end();
}).listen(8081);



Question: How to Execute above response in browser?
http://127.0.0.1:8081/
You should be already installed WampServer/Xampp Server.


Question: How to install httpdispatcher?
npm install httpdispatcher



Question: Give an example of http GET Request?

dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});



Question: Give an example of http POST Request?

dispatcher.onPOST("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('<h3>
Received POST Data</h3>
');
});



Question: Give an full example of httpdispatcher which have multiple pages?

var dispatcher = require('httpdispatcher'); 
function handleRequest(request, response) {
    try {
        //log the request on console
        console.log(request.url);
        //Disptach
        dispatcher.dispatch(request, response);
    } catch (err) {
        console.log(err);
    }
}
dispatcher.setStatic('resources');

//A sample GET request    
dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});

dispatcher.onGet("/aboutus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
About US Page</h3>
');
});


var http = require('http');
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(8081, function() {
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", 8081);
});




Saturday 12 October 2019

How to install and Connect to MySQL in NodeJS?

How to install and Connect to MySQL in NodeJS?

Hope you have already installed nodeJS, If not Please install first.
https://nodejs.org/en/download/

Question: How to install new package in nodejs?
npm install packagename



Question: How to install MySQL?
npm install mysql



Question: How to update MySQL?
npm update mysql



Question: How to include MySQL?
var mysql = require("mysql");



Question: How to connect to MySQL in nodeJS?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to connect to MySQL in single string in nodeJS?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/database'); 
con.connect(function(err) {
    if (err) {
        console.log('Error connecting to database');
        return;
    }
    console.log('Connection established Successfully');
});



Question: How to get records from MySQL database in node.js?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "enterprisedev2"
});

con.query('SELECT * FROM admin_members where id<=10 ', function(err, rows) {
    for (var i = 0; i < rows.length; i++) {
        console.log(rows[i]);
    }
});


Question: How to insert record in database?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/mydb');
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
con.query('INSERT INTO messages set ?', post, function(err, result) {
    if (err) {
        console.log(err.message);
    } else {
        console.log('record added in db');
    }
});



Question: How to print the query while inserting record?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/mydb');
var post = {
    'userID': "1",
    'userName': 'username',    
    'device': 'web',
    'stream_time': "0",
    'user_display_name': "arun kumar gupta",
    'user_photo': "hello"
};
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: Given another way to insert data in MySQL Database?
var mysql = require("mysql");
var con = mysql.createConnection('mysql://arun:arun@localhost/enterprisedev2');

/* data insert in db */
var postData = {
    userID: "1",
    userName: "arunkg",
    userRole: "1",
    text: 'kkkkkkkkkkkkkkkk',
    status: "1",
    vid: '21'
};

var mysqlProfiler = con.query('INSERT INTO `messages` (`userID`, `userName`, `userRole`,`text`,`status`,`vid`) VALUES (' + [postData.userID, mysql.escape(postData.userName), postData.userRole, mysql.escape(postData.text), postData.status, postData.vid] + ')', function(err, result) {
    if (err) {
        //console.log(err.message);
    } else {
        console.log('record added in db');
    }
});



Monday 4 March 2019

Node JS Interview Questions and Answers

Node JS Interview Questions and Answers

Question: What is callback?
A callback function is called at the completion of a given task.


Question: What Are Arrow Functions?
Arrow functions – also called "fat arrow" functions, are a more concise syntax for writing function expressions.

Examples
const multiplyES6 = (x, y) => { return x * y };
const phraseSplitterEs6 = phrase => phrase.split(" ");
var docLogEs6 = () => { console.log(document); };



Question: What is JSON.stringify()?
JSON.stringify() method converts a JavaScript object to a JSON string.


Question: What is Handlebars view engine in nodejs?
Handlebars.js is templating engine in NodeJS.


Question: What is an error-first callback?
Error-first callbacks are used to pass errors and data.
You have to pass the error as the first parameter, and it has to be checked to see if something went wrong.


Question: What are Promises?
The Promise object represents the event completion or failure of an asynchronous operation, and its resulting value.
function readFile(filename, enc){
  return new Promise(function (resolve, reject){
    fs.readFile(filename, enc, function (err, res){
      if (err) reject(err);
      else resolve(res);
    });
  });
}



Question: What is callback hell in Node.js?
Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain.


Question: What is the role of REPL in Node.js?
Full form of REPL is Read Eval print Loop.


Question: Explain chaining in Node.js?
Chaining is a mechanism whereby the output of one stream is connected to another stream as input.


Question: How to access the GET parameters after ? in Express?
req.query.name;



Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers.


Question: How we exporting a Module?
We use export for exporting the module.
exports.sayHelloInEnglish = function() {
    return "Hello, how are you?";
};



Question: What is meaning of tilde and caret?
the tilde(~) matches the most recent minor version.
the caret(^) matches the most recent major version.


Question: How to access 2nd argument when passed in command line?
process.argv.slice(3,4); //two=222



Question: What is Yargs?
Yargs helps to parsing arguments of command line tools.



Question: What is Async?
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
    // results is now an array of stats for each file
});



Question: How to use expressJs in Node
var express = require('express');
var app = express();

//Add cookie to express
var cookieParser = require('cookie-parser');
app.use(cookieParser());

//Add session to express
var session = require('express-session');
app.use(session({
    secret: 'XEDDKJKXD',
    name: 'testname',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));

//Add static path
app.use(express.static('public'))

//Add "Parse JSOn" to express
var bodyParser = require('body-parser')
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
    extended: true
}));

//Add middleware to express
app.use(function (req, res, next) {
  //console.log('Time2222:', Date.now())
 res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   
  next()
})


//Add https to expresJs
var https = require('https');
var privateKey  = fs.readFileSync('public/cert/server.key', 'utf8');
var certificate = fs.readFileSync('public/cert/georama.crt', 'utf8');
var caCertificate = fs.readFileSync('public/cert/chain.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate, ca: caCertificate};
var httpsServer = https.createServer(credentials, app);   


Question: How to start node on port?
httpsServer.listen(config['SERVERPORT'],function() {
    console.log('https listening on *:' + config['SERVERPORT']);
});



Question: How to connect socket with https?
var io = require('socket.io')(httpsServer);



Question: What is underscore module in nodeJS?
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
console.log(_.each([1, 2, 3], function(value, key){
     console.log(key+'>>'+value)
 }));



Question: What Are Core Features Of Express Framework?
1) Allows to set up middlewares to respond to HTTP Requests.
2) Defines a routing.
3) Dynamically render HTML Pages.


Question: Give simple example of ExpressJS?
var app = require('express')();
var http = require('http').Server(app);

app.get('/listing', function (req, res) {   
   res.send('This is listing API'); 
});

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



Question: What are different Middleware?
1) Application-level middleware
2) Router-level middleware
3) Error-handling middleware
4) Built-in middleware
5) Third-party middleware



Tuesday 5 February 2019

Node Js Buffer module examples with script code

Node Js Buffer module examples with script code

Question: What is buffer module?
Buffer class provides instances to store binary data similar to an array of integers. Buffer class is a global class that can be accessed in an application.


Question: How to create an empty buffer object?
var bufferData=Buffer.alloc(1024); //1024 bytes



Question: How to write in buffer object?
var bufferData.write('this is string'); //write only string



Question: How to create an array of buffer?
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
console.log(bufferData);//

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
console.log(arrayObject);



Question: What is concat? How to concate the buffer data?
Concatenates an array of Buffer objects into one Buffer object
var buf1 = Buffer.from('1');
var buf2 = Buffer.from('2');
var buf3 = Buffer.from('3');
var bufferData = [buf1, buf2, buf3];
bufferData=Buffer.concat(bufferData);

OR
arrayObject=[];
arrayObject.push(Buffer.from('1'));
arrayObject.push(Buffer.from('2'));
arrayObject.push(Buffer.from('3'));
bufferData=Buffer.alloc(1024);
bufferData = Buffer.concat(arrayObject);
console.log(bufferData);



Question: How to compare two buffer?
var buf1 = Buffer.from('abc');
var buf2 = Buffer.from('abc');
var compare1 = Buffer.compare(buf1, buf2);
console.log(compare1); //0

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var compare2 = Buffer.compare(buf1, buf2);
console.log(compare2); //-1

var buf1 = Buffer.from('b');
var buf2 = Buffer.from('a');
var compare3 = Buffer.compare(buf1, buf2);
console.log(compare3); //1



Question: How to check if data is buffer?
Buffer.isBuffer(obj);//true|false



Thursday 20 December 2018

Node JS tutorial for beginner

NodeJS Framework Understanding

Question: What is NodeJS
Node.js is a platform built for fast and scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. It can be used in Websites application, Android applicationa and IOS application etc.


Question: What type of framework is Nodejs?
NodeJS is JavaScript-based framework/platform



Question: Is Nodejs Server OR Cient Side?
Both, Node work for both.



Question: What is REPL?
REPL stands for Read Eval Print Loop
Node.js comes with virtual environment called REPL (also Node shell).


Question: What are most common REPL Commands?
ctrl + c
Terminate the current command.
ctrl + c twice 
terminate the Node REPL.
Up/Down Keys
see command history.
tab Keys
list of current commands.
.help
list of all commands.
.break
exit from multiline expression.
.save filename 
save the current Node REPL session to a file.
.load filename
load file content in current Node REPL session.



Question: How to exist from REPL?
ctrl + c twice 



Question: How to install module in NodeJS?
npm install express
for install express.


Question: How to uninstall module in NodeJS?
npm uninstall express
for uninstall express.