Tuesday, 15 June 2010

javascript - Global objects with Node.js + Express -



javascript - Global objects with Node.js + Express -

i'm studying node.js + express, coding basic login example. /login route set within routes/login.js file:

var express = require('express'); var router = express.router(); var mysql = require('mysql'); var connectionpool = mysql.createpool({ host : 'localhost', user : 'user', password : 'pass', database : 'database' }); router.post('/', function(req,res){ connectionpool.getconnection(function(err, connection) { if (err) { console.error('connection error: ',err); res.statuscode = 503; res.send({ result: 'error', err: err.code }); } else { // } }); }); module.exports = router;

i wondering: how can create mysql or connectionpool visible in entire application? don't want redeclare them on each route file i'll create. i'm looking include or require method.

any idea?

create separate module deed interface retrieving sql connections so:

var mysql = require('mysql'); var connectionpool = mysql.createpool({ host : 'localhost', user : 'user', password : 'pass', database : 'database' }); exports.getconnection = function (callback) { connectionpool.getconnection(callback); };

just require in file perform db interaction so:

var connections = require('./connections'); connections.getconnection(function (err, c) { // utilize c connection });

javascript mysql node.js

No comments:

Post a Comment