Passing Object with module exports - javascript

I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.

Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};

Related

How to display data from MySQL into HTML-Page with NodeJS

I'm new in Node JS and I'm trying to display the fetched data from my MySQL Table into a table in my HTML-File. But I couldn't find anything that helped me. I would really appreciate it if somebody can help me to get a solution! :)
Here's my js-code:
//app.js
// Get the mysql service
var mysql = require('mysql');
var express = require('express');
var app = express();
app.get('/', function (request , response) {
fetchData(response);
console.log('Done. Displayed Data.');
});
// Add the credentials to access your database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'Breunninger',
port: '3306'
});
// connect to mysql
connection.connect(function(err) {
if(err){throw err;}
console.log('Connected');
});
function executeQuery(sql, cb){
connection.query(sql, function( result, fields){
cb(result);
})
}
function fetchData(response){
executeQuery("SELECT username, tor, datum, sendungsstruktur FROM Buchung JOIN user ON(user.id = Buchung.userid)", function (result) {
console.log(result);
response.write('<div class="container-wrap"><table id="example" class="display"><tr>');
for(var column in result[0]){
response.write('<td> <label>' + column + '</label></td>');
response.write('</tr>');
}
for(var row in result){
response.write('<tr>');
for(var column in result[row]){
response.write('<td>' + result[row][column]+ '</td>');
}
response.write('</tr>');
}
response.end('</table></div>');
});
}
<div class="container-wrap">
<div class="flexslider">
<script src="app.js"></script>
</div>
</div>
There's a small (but critical!) error in the executeQuery function, the first argument should be the error object, so if you can re-write this as below your query should work.
function executeQuery(sql, cb){
connection.query(sql, function( error, result, fields){
if (error) {
console.error("An error has occurred:", error);
} else {
cb(result);
}
})
}
Node callback usually reserve the first argument for an error object, it's easy to miss this!
Also, we should be clear, the Node.js Express code will be running on the server side, so to see the results you need to point your browser to the host and port this is serving, e.g. http://localhost:3000/ (if you do:)
app.listen(3000);

Canno add values to database by javascript

I am getting an error on node.js, and I cannot identify why. Can anybody help me? If I add only 1 data from the array it gets added to the database. However, when I add other inputs, it displays an error in node.js and doesn't get saved in my database.
var express = require('express');
var app = express();
app.get('/register/*', handleGetRequest); //how do I pass usrName here?
app.use(express.static('public'));
app.listen(5000);
function handleGetRequest(request, response){
var pathArray = request.url.split("/");
var pathEnd = pathArray[pathArray.length - 1];
if(pathEnd === 'register'){
response.send("{working}");
//console.log(request.body.usrName);
}
else
var registerArray = pathEnd.split("&");
response.send(JSON.stringify(registerArray));
saveToDb(registerArray);
// response.send("{error: 'Path not recognized'}");
}
function saveToDb(registerArray){
for (var i = 0; i < registerArray.length; i++) {
console.log(registerArray[i]);
}
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'customer',
port: 6000
});
con.connect();
addData();
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001,"+registerArray[0]+"," +registerArray[1]+"');",function(err, result,
fields){
if (err) throw err;
console.log('results' , result);
}
);
}
//Close the connection
con.end();
}
You are missing single quotes in your SQL statement that cause the problem. The code should look like this:
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001','"+registerArray[0]+"','" +registerArray[1]+"');",
function(err, result, fields) {
if (err) throw err;
console.log('results' , result);
}
);
}

can't make nodejs mysql query results a global variable

I'm trying to use the mysql module to get some data from a mysql database and then write it to an HTML page but it seems stuck inside the query function itself.
The code looks like this:
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
The first console.log outputs the results properly, but the second one returns the empty array as declared in the first line and prints first. I'm new to Javascript so I'm probably missing something very obvious. Thanks in advance.
I think you are recreating another variable because adding "var " before. Have you tried without it?
If it doesn't work, here another posible solution:
global.rooms = [];
global.rooms = result;
https://nodejs.org/api/globals.html#globals_global
var rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
you missed out to declare rooms as global variable.
approach using a callback function
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
function query(callback) {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
callback(rooms);
console.log(rooms[9]);
});
});
}
function log_it_out() {
console.log(rooms);
}
query(log_it_out);
I don't think it matters for you anymore since it's been roughly a year since you asked this basic question, however maybe someone else that searches for this question might find this information helpful since I had the same problem.
**} else if(req.url === "/api/labeat") {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(information));**
IMPORTANT
When you try to return something to a website beside the variable declarations, when you use res.end();, make sure to turn the result or whatever kind of information you're trying to work with into a string or buffer since the res.end() expects either a string or a buffer. Also specify the Content-Type as I did (application/json).

Meteor.js MYSQL output to template

I am new to node and meteor.js. I am trying to wrap my head around some of the basic functionality coming from PHP/MYSQL.
I am trying to work with the node npm MYSQL to output a list of data to a template file, but can't seem to get the data to connect to the template. I can get the data to output to console.log - but not to the template.
Here is my server connection.
var eventName = [];
if (Meteor.isServer) {
Meteor.methods({
'geteventName': function () {
this.unblock();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
socketPath : '...socketpath',
database : 'database'
});
connection.connect();
connection.query('SELECT eventName FROM events', function(err, rows, fields) {
if (err) throw err;
for (var i = 0; i < rows.length; i++) {
eventName.push(rows[i]);
};
//console.log(eventName);
return eventName;
});
connection.end();
//return "some return value";
}
});
}
if (Meteor.isClient) {
Meteor.call('geteventName', function (error, result) {
console.log(result);
});
}
** I have updated the code based on the comments, but the Meteor call just returns undefined. If I set a general variable to return - i.e. I just had it set to some dummy text, the results passes through to the client and returns in the console.

return node.js-mysql results to a function

I've got two node.js files: server.js and database.js. I want my socket.io emitting to happen in server.js and the database queries in database.js. Server.js:
// init
io.sockets.on('connection', function(socket) {
initdb = db.initdb();
console.log(initdb)
});
My database.js contains basically the following code:
function query(queryString) {
connection = mysql.createConnection({
host: '12.23.45.67',
user: 'user',
password: 'password',
database: 'database'
});
connection.connect();
var res = connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
});
connection.end();
}
// export initdb for external usage by server.js
exports.initdb = function() {
var initdb = query("SELECT * FROM columns;");
};
My problem is that I want the rows object from within the connection.query function to be returned to my initdb function. However the only place where I can log this object is within that function. How can I pass the query results so I can emit the JSON object it from server.js?
Remember that node is asynchronous. So for the most part, you get data back through callbacks rather than as return values to functions.
You'll need to chain a callback through to where your query happens, something like:
// in database.js
exports.initdb = function(cb) {
query("SELECT * FROM columns", cb)
}
function query(queryString, cb) {
// .. stuff omitted
var res = connection.query(queryString, function(err, rows, fields) {
connection.end();
if (err) return cb(err);
cb(null,rows);
});
// in server.js
io.sockets.on('connection', function(socket) {
db.initdb(function(err,rows) {
if (err) {
// do something with the error
} else {
console.log(rows)
}
});
});
The callback would be a function taking 2 parameters, err and rows. Your server.js code would need to check the value of err and act accordingly, otherwise it would have the rows.

Categories

Resources