cannot response.write on connection node.js - mysql

I wrote this code in node.js :
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('start\n');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'hostname',
user : 'user',
password : 'pass',
database : 'dbname',
});
connection.connect();
connection.query('SELECT code FROM user_type', function(err, rows, fields) {
if (err) throw err;
//This for is to run on all the results
for(var i=0;i<2;i++){
res.write('name:',rows[i].code);
}
});
connection.end();
res.end('End');
}).listen(8080);
console.log('Server running');
my questions are:
1. why did the res.write in the for loop print nothing in my html page?
2. what to write instead of 2 in the for?

The issue is the timing of execution.
Since connection.query() is asynchronous, it delays the execution of the callback function to when the query finishes, but allows the surrounding block of code to continue in the meantime. This results in res.end('End') being executed before res.write('name:',rows[i].code).
To also delay res.end(), move it inside the callback:
connection.query(..., function(err, rows, fields) {
if (err) throw err;
for (...) {
res.write('name:',rows[i].code);
}
res.end('End');
});
rows should be an Array when there isn't an err, so you can use its length property:
for (var i = 0; i < rows.length; i++) {
It's also a common practice to store the value of length in a local variable:
for (var i = 0, len = rows.length; i < len; i++) {

Related

connect nodejs to mysql

I have following code that connect nodejs to mysql. When I run it the first time it work the data print out to the page but when I refresh the page it tell 'This site can’t be reached' 'localhost refused to connect.' I don't understand why I can connect to server only the first time. I use url as localhost:3000/car
var express = require('express');
var app = express();
app.use(express.static(__dirname));
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'joeM',
password : 'versus',
database : 'joe'
});
app.get('/car', function(req, res){
connection.connect();
connection.query('SELECT * FROM test1', function(err, rows, fields) {
if (err) throw err;
var print = '<ol>';
for( var i = 0; i<rows.length; i++){
print +=('<li>ID:' + rows[i].id + ' Brand:' + rows[i].brand +'</li>' );
}
print += '</ol>';
res.send(print);
connection.end();
});
});
app.listen(3000, function(){
console.log('Magic Happen at port: 3000');
});
dont use connection.connect(); in every request and set it out of request block

Node/Express + MySQL: Inserts not displaying instantly

I have a form called #add_blog_post with the action "/mysql_test/add_blog_post" and method of "POST"
Jade markup:
form#add_blog_post(action="/mysql_test/add_blog_post" method="POST")
This form executes the following code in my app.js:
app.post('/mysql_test/add_blog_post', function(req, res) {
var author = req.body.author;
var date = req.body.date;
var title = req.body.title;
var body = req.body.body;
var blog_insert_query = "insert into 332project.blog(author,date,title,body) values(";
blog_insert_query += ("'"+author+"'"+","); blog_insert_query += ("'"+date+"'"+","); blog_insert_query += ("'"+title+"'"+","); blog_insert_query += ("'"+body+"'"+")");
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS
});
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query(blog_insert_query, function(err, result) {
res.redirect('/mysql_test');
});
});
The blog post insert works just fine but the website takes a while for the insert to be displayed from the select statement on /mysql_test.
Here is my route:
var express = require('express');
var router = express.Router();
var db_calls = require('../db.js');
var connection = db_calls.connect();
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query("select * from 332project.blog order by id desc", function(err, rows, fields) {
connection.end();
if (!err) {
result = rows;
}
});
router.get('/', function(req, res, next) {
res.render('mysql_test', {
result: result
});
});
module.exports = router;
What gives? It almost seems like a caching issue. I'd really like for my create/update operations to be instantly visible in my application.
Source code: https://github.com/harwoodjp/learning-express
Your problem is probably that you're not calling connection.end() per the docs.

Whats wrong with this express code?

Hello i am trying to check two mysql values and if its matching anything in the database it needs to generate a token but it does not seem to work :(
Everytime i run this code i get a connection time out:
var express = require('express');
var router = express.Router();
var mysql = require("mysql");
var randomstring = require("randomstring");
/* GET users listing. */
router.get('/', function(req, res, next) {
// First you need to create a connection to the db
var connection = mysql.createConnection({
host: "localhost",
user: "segfault",
password: "wnk9ctte2endcKzBKtre7auE",
database: "segfault"
});
connection.connect();
var input_user = req.body.username;
var input_pass = req.body.password;
var token = randomstring.generate(12);
connection.query('SELECT username FROM segfault.users AS username', function(err, rows, fields) {
if (err) throw err;
for(var i in rows){
username = rows[i].username;
if(input_user == username){
connection.query('SELECT password FROM segfault.users AS password', function(err, rows, fields) {
if(rows[i].password == input_pass){
res.send("OK: "+ token);
console.log("OK:" + token)
}
});
}
}
});
connection.end();
});
module.exports = router;
tell me please what i am dooing wrong!
You close the connection to the database without waiting for the result of the query.
Move connection.end(); inside callback after the res.send.

Res.write is not working when continuously sending UDP packet

//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express'), fs= require('fs'),path = require('path'),util = require('util'),dgram= require('dgram'),client= dgram.createSocket('udp4'),bodyParser = require('body-parser'),app = express(), ejs = require('ejs');
var plotly = require('plotly')("Patidar", "ku0sisuxfm")
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static('public'));
//Reading in the html file for input page
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//reading in html file for output page
app.get('/output', function(req, res){
var html = fs.readFileSync('index4.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//Recieving UDP message
app.post('/output', function(req, res){
var once= req.body.submit;
if (once == "Once") {
//Define the host and port values of UDP
var HOST= req.body.ip;
var PORT= req.body.port;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});
//Recieving message back and printing it out to webpage
client.on('message', function (message) {
fs.readFile('index3.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp = message.toString(); //here you assign temp variable with needed value
var renderedHtml = ejs.render(content, {temp:temp, host: HOST, port: PORT}); //get redered HTML code
res.end(renderedHtml);
//var data = [{x:[req.body.number], y:[temp], type: 'scatter'}];
//var layout = {fileopt : "overwrite", filename : "simple-node-example"};
//plotly.plot(data, layout, function (err, msg) {
//if (err) return console.log(err);
//console.log(msg);
//});
});
});
}
if (once == "continuous") {
var timesRun = 0;
var requestLoop = setInterval(function(){
timesRun += 1;
if(timesRun === 5){
clearInterval(requestLoop);
}
//Define the host and port values of UDP
var HOST= req.body.ip;
var PORT= req.body.port;
//Reading in the user's command, converting to hex
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});
//Recieving message back and printing it out to webpage
client.on('message', function (message) {
fs.readFile('index3.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp = message.toString(); //here you assign temp variable with needed value
var renderedHtml = ejs.render(content, {temp:temp, host: HOST, port: PORT}); //get redered HTML code
res.write(renderedHtml);
//var data = [{x:[req.body.number], y:[temp], type: 'scatter'}];
//var layout = {fileopt : "overwrite", filename : "simple-node-example"};
//plotly.plot(data, layout, function (err, msg) {
//if (err) return console.log(err);
//console.log(msg);
//});
});
});
}, 10000);
}
});
//Setting up listening server
app.listen(3000, "192.168.0.136");
console.log('Listening at 192.168.0.136:3000');
I have two button, one button sends the UDP packet once, while a continuous button sends the same UDP packets every 10 seconds. However, when this button is pressed, res.write is repeating the entire output again. Look at the attached pic to see output[![enter image description here][1]][1]
After putting your code into an auto-code-formatter to make it readable, I can see that you are doing this:
client.on('message', function (message) { ...
inside of your app.post() handler. That means that every time your post handler is called, you add yet another client.on('message', ...) event handler. So, after it's called the 2nd time, you have two event handlers, after it's called the 3rd time, you have three and so on.
So, as soon as you have these duplicate, each will get called and you will get duplicate actions applied.
Your choices are to either:
Use .once() for the event handler so it is automatically removed after it fires.
Remove it manually after it fires or when you are done with it.
Add it once outside your app.post() handler so you never add duplicates.
Restructure the way your code works so it doesn't have this type of issue. For example, you have two different handlers for the same incoming message. This is a sign of very stateful code which is more complex to write properly. A better design that isn't stateful in that way would be simpler.

Read, Display and Insert into another Table

I am new to NodeJS programming,
Have created a script which reads from Database table nodetest having 50K records and displays in the browser and then writes to another table called 'nodetestcopy'
var express = require('express');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
var rows={};
var copyOfrows={
'id':null,
'f_name':null,
'l_name':null,
'title':null
};
var date1 = (new Date()).getTime();
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : null, //port mysql
database:'test'
},'request')
);
app.get('/api/entries', function(req, res){
req.getConnection(function(err, connection) {
if(err) {
console.log(err);
res.status(500).send('Cannot get database connection');
} else {
connection.query("select * from nodetest", function(err, rows) {
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.write(''+JSON.stringify(rows));
var date2 = (new Date()).getTime();
console.log('Cnt : '+rows.length+' Took Time to execute :'+(date2 - date1)/(60*60));
//console.log(rows);
//Now insert in another table ' nodetestcopy'
for(var i in rows){
connection.query("insert into nodetestcopy set ?", rows[i], function(err, rows) {
if(err) {
console.log(err);
//res.status(500).send(err);
} else {
}
});
}
}
});
}
});
});
app.listen(3000);
This script is working for the first time, and when I refresh the browser for second time, getting an error .
Please guide me what is going wrong here and also Is my approach is correct?
Looping the record for 50K times for(var i in rows){ ...}
Please give a feasible solution for this, and correct me wereever the code is wrong.
Thanks
What is the error message that you are getting? Also, another way to avoid hitting the database with multiple queries could be to combine the records in one query and then make one database insert call, like:
var query = 'insert into nodetestcopy values("';
for (var i in rows) {
query += rows[i] + '"';
if (i < rows.length) query += ',';
}
query += ')';
connection.query(query, function(err, rows) { ...