I can't receive data from custom module in node.js -
i wrote module called accountmanager.js
var sqlite3 = require('sqlite3'); var db = new sqlite3.database("./users.db"); exports.userexists = function userexists(nickname) { var stmt = 'select * users login="' + nickname + '"'; db.each(stmt,function(err,row) { if(row) { if(row.login==nickname) return true; else return false; } }); }
in main app.js file i've got
var accountmanager = require('./lib/accountmanager'); console.log(accountmanager.userexists('user1'));
this app says 'undefined' in console... checked module working fine, guess it's problem callback? please, give me help, don't understand wrong code...
you need understand how asynchronous functions , callbacks work.
basically cannot return inside callback need invoke callback pass userexists
.
var sqlite3 = require('sqlite3'); var db = new sqlite3.database("./users.db"); exports.userexists = function userexists(nickname, cb) { var stmt = 'select * users login="' + nickname + '"'; db.each(stmt,function(err,row) { if(row) { cb(row.login == nickname); } }); }
to use it:
accountmanager.userexists('user1', function(found) { console.log(found); });
besides that, code has gaping sql injection hole , might not intend do. here's fixed version of userexists
function:
exports.userexists = function userexists(nickname, cb) { var stmt = 'select count(*) cnt users login = ?'; db.get(stmt, nickname, function(err, row) { cb(row.cnt > 0); }); };
why better?
- you not interpolate value in sql string (which bad, have escape stuff avoid sql injection). passing separately cleaner , better
- you want know if user exists. retrieve count (which 1 row). if it's not 0 user exists.
- now callback invoked. in first example more closely based on code invoked in case user has been found - not wanted.
Comments
Post a Comment