Node.js Synchronous Queries with MySQL

I am working on creating a user registration system for a website that I am working on, but I have a few problems.

I try to stay away from having to insert callbacks because it gets dirty. I need help if you find out if there is a way to create synchronous queries using node -mysql

This is what I am trying to achieve.

connection.query("select 1 as email from users where email = " + connection.escape(email), function(err, rows, fields) { if(err) { var error = { error_message: err.code, error_number: err.errno }; return res.send(error); } if(rows.length > 0) { var error = { message: 'Email Address is Taken', code: 2 }; return res.send(error); } }); connection.query("insert into users (email, password) values ("+connection.escape(email)+", "+connection.escape(hash)+")", function(err, rows, fields) { if(err) { var error = { error_message: err.code, error_number: err.errno }; return res.send(error); } }); 

My goal is to execute the first query, and if it returns a string and then does not execute the second query, but if the first query returns 0 rows, continue and run the second query.

I know that I can embed the second request in the first request and put, if in another, but what I do not want to do, because when I have these two requests, I also have the option to use bcrypt to encrypt the password, which should also be nested.

Is there a way to write it down so that I don’t need to insert two queries or nesting them will be my only option?

+8
source share
5 answers

As jfriend00 said above, if you are going to develop in node.js, then you MUST become comfortable writing asynchronous code.

Chained promises is probably the best choice:

ADDITION:

This tutorial shows integer combining using node.js SQL queries. It also discusses how you can use Q and / or Step to simplify the code:

+12
source

You can simply use the module for node, which provides synchronous functions. Here you will find a module that provides sync / async functions for working with mysql.

https://github.com/Will-I4M/node-mysql-libmysqlclient

Here's how you could use it to execute a synchronous request:

 var config = require("./config.json") ; var mysql = require('mysql-libmysqlclient') ; var client = mysql.createConnectionSync(config.host, config.user, config.password, config.database) ; var query = "SELECT * FROM Users ;" ; var handle = client.querySync(query) ; var results = handle.fetchAllSync() ; console.log(JSON.stringify(results)) ; 
+15
source

For most of the things I code in node.js, I like asynchronous code. However, I fully understand that asynchronous code is extremely and dangerously incompatible with the need to write and maintain business logic. I have used many alternative methods. Modules that make things synchronous still leave problems with scopes that complicate things. Promises worked best for me. Using this approach, I practically wrote an interpreter for the new language on top of JavaScript. I may seem absurd, but the most practical and safe way for me was to use the shelljs module and the mysql shell client. This is not a good execution performance, but it provides much better performance for developers and provides a clear and orderly business logic, which is extremely important for business logic. Here is a snippet of code to give an example of what I created:

 var shell = require('shelljs'); module.exports = { user: '', password: '', runSql: function (sql) { var command = "echo '" + sql.replace(/'/g, "'\\''") + "' | mysql -u" + this.user.replace(/'/g, "'\\''") + " -p'" + this.password.replace(/'/g, "'\\''") + "'"; var raw = shell.exec(command, {silent: true}).stdout; //console.log( 'BASH -> MySQL YIELD: "' + raw + '"' ); if (raw.substr(0, 5) === 'ERROR') { console.log('ERROR Resulting from: ' + sql + '\n' + raw); return []; } var rows = raw.split('\n'); var names = []; for (var r = 0; r < rows.length; r += 1) { columns = rows[r].split('\t'); // Capture column names if (r === 0) { names = columns; continue; } // Reformat row into named valued var fields = {}; for (var c = 0; c < columns.length; c += 1) { fields[names[c]] = columns[c]; } rows[r] = fields; } // Eliminate extraneous first and last rows rows.splice(0, 1); rows.splice(rows.length - 1, 1); return rows; }, } 
0
source

There may be conditions when you need to synchronize requests (or at least for readability or simplicity). I do not agree that everything should be done asynchronously in node.js.

I tested many available solutions and ended up with the "sync-mysql" module ( https://github.com/ForbesLindesay/sync-mysql ).

Easy to install and use, but not so good in performance (especially if you need to perform many subqueries).

0
source

I know I'm late for this party, but I feel that I can help people like me who needed a way to use MySQL synchronously.

The answer is here .

Yes, and I had to add pool.end (); after my request code to close the connection and stop the infinite wait loop. Look here

0
source

All Articles