Node will call the anonymous function you specified in "query.on('result', ..." when results come in, which will be asynchronously -- later -- after you've created and logged str.
You need to define a function, which accepts a callback parameter which the function will call when it has put together the full string. Here is an untested example:
function definition:
function getXml(cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : DB_USER,
password : DB_PASS,
database : DB_NAME,
});
connection.connect();
var str = '<products>';
var query = connection.query('SELECT * FROM tbl_product limit 0,3');
query.on('error', function (err) {
cb(err);
});
query.on('result', function (row) {
str += '<product_name>' + row.product_name + '</product_name>';
});
query.on('end', function () {
str += '</products>';
cb(null, str);
});
}
usage:
getXml(function(err, xml) {
if (err) throw err;
console.log(xml);
});
You would probably want to do the connection to the database outside of the function instead but I'm keeping it in since I don't know the structure of the rest of your application.
Note also that you'll want to escape row.product_name somehow. (Think about what would happen if row.product_name contained "<" or ">".)