Friday, 3 February 2017

How to execute MySQL queries in node.js?

How to execute MySQL queries in node.js?

Question: How to install mysql in nodeJS?
npm install mysql



Question: How to update mysql in nodeJS?
npm update mysql



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



Question: How to connect to MySQL in nodeJS?
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "mydb"
});



Question: How to handle error while connecting to MySQL in nodeJS?
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 insert record in database with nodeJS?
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: How to print SQL query in nodejs?
var mysqlProfiler = con.query('INSERT INTO messages set ?', post, function(err, result) {});
console.log(mysqlProfiler.sql);



Question: How to insert record in database - Full Example?
var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "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); //print the query



Question: How to fetch all records in nodeJS?
var uid=1002;
 mysqlConn.query('SELECT * FROM `messages` WHERE id = '+uid , function (error, results, fields) {
    if (results != null && results.length > 0) {
        for each (var results in res) {
            console.log(res);
         }
    }
}



Wednesday, 25 January 2017

How to make a node.js application run permanently

How to make a node.js application run permanently

  1. Open putty
  2. Login to ssh with username and password
  3. Go to the folder where node file exist.
  4. Execute following command
  5. nohup node server.js &

    then execute following command
    rm nohup.out

  6. Now you can close the putty


Question: How to check nodeJS running?
top

Just look for "node", If its shown means running.



Question: How to stop/kill the node?
Get the "process id" from terminal and kill the same.
kill PROCESS_ID

OR
killall node



How to search the process using command?
ps -fC node