I am completely new in Node.js and i do not know how to call or use a function in Node.js. I created one function connectWithDatabase() and i want to check if it fetch data from table and returns value.
This code works fine if i will add this function code router.get('/', function(req, res)
BUT if i will create a function connectWithDatabase() and try to call it, this function will return 0. value= result.rows.length; does not assign value, I am have no idea how to fix this and how to create a "callback" function.
Kindly help...
var connectWithDatabase = function(){
var conString = databasehelper.conString;
console.log(conString);
var client = new pg.Client(conString);
var value = 0;
pg.connect(conString, function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
client.query("SELECT * FROM users", function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows);
value= result.rows.length;
console.log("result.rows.length " + result.rows.length);
client.end();
done();
//output: 1
});
});
console.log("value " + value);
return value;
}
/* GET home page. */
router.get('/', function(req, res) {
var value = connectWithDatabase();
console.log("value " + value);
res.render('index');
});