I'm playing with node.js and express. I have a little server which fetch sqlite contents and send everything to a Jade template. It works fine using this code :
var express = require('express');
var app = express();
app.set('view engine', 'jade');
var async = require('async');
var result_title = [];
var result_scope = [];
var result_benefits = [];
var result_technical = [];
app.use(express.static(__dirname + '/views'));
app.get('/product1', function(req, res){
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('products.db');
var check;
db.serialize(function() {
db.each("SELECT title, scope, body, technical_information FROM products", function(err, row) {
result_title.push(row.title);
result_scope.push(row.scope);
result_benefits.push(row.body);
result_technical.push(row.technical_information);
});
});
console.log(result_title[0]);
res.render("index", {title:result_title[0], scope:result_scope[0],benefits:result_benefits[0], technical_information:result_technical[0]});
db.close();
});
app.listen(8080);
My issue is that when I go to page http://localhost/product1:8080 nothing is displayed. A manual refresh of the page is needed to load the content! My research tells me that I need to use Async functions. I edited my code :
var express = require('express');
var app = express();
app.set('view engine', 'jade');
var async = require('async');
var result_title = [];
var result_scope = [];
var result_benefits = [];
var result_technical = [];
app.use(express.static(__dirname + '/views'));
app.get('/product1', function(req, res){
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('products.db');
var check;
async.series([
function(callback) {
db.serialize(function() {
db.each("SELECT title, scope, body, technical_information FROM products", function(err, row) {
result_title.push(row.title);
result_scope.push(row.scope);
result_benefits.push(row.body);
result_technical.push(row.technical_information);
});
});
},
function(callback) {
// console.log(result_title[0]);
res.render("index", {title:result_title[0], scope:result_scope[0],benefits:result_benefits[0], technical_information:result_technical[0]});
db.close();
}
], function(error, results) {
console.log('');
})
});
app.listen(8030);
But the webpage is loading, loading and nothing happens.. I made something wrong, but no idea where for the moment. If someone have an idea it could be great ;-) Thanks!