Accessing MariaDB from JavaScript Using Node.js and Node-MariaSQL

1. If you have not already done so, download and install Node.js. Details are given in a previous post.

2. If you have not already done so, download and install Python, which is unfortunately required to run the next step. A specific version of Python must be used, as the various versions are evidently not interchangeable in this instance. As of this writing, the correct version is 2.7, which is available at the URL “http://www.python.org/download/.” It may also be necessary to set the value of the “PYTHON” environment variable to “C:\Python27\Python.exe”.

3. Download and install MariaDB. As of this writing, the latest version can be found at the URL “https://downloads.mariadb.org/.” Follow the prompts presented by the installer, and make a note of the password for the “root” user.

4. In any convenient location, create a new directory named “NodeJSMariaDBTest”.

5. Install the Node-MariaSQL “binding” for Node.js by opening a command prompt, navigating to the newly created “NodeJSMariaDBTest” directory, and entering the command “npm install mariasql”. Several status messages will appear, and the Node-MariaSQL package will be downloaded and installed. The entire process may take several minutes. More information on the Node-MariaSQL project can be found at the URL “https://github.com/mscdex/node-mariasql.

6. Still in the NodeJSMariaDBTest directory, create a new text file named “NodeJSMariaDBTest.js”, containing the text shown below. Substitute the root user’s actual password (which you should have noted in the previous step) where the text “Password42” appears. Note that this code was adapted from a sample found at the URL https://github.com/mscdex/node-mariasql.

// adapted from https://github.com/mscdex/node-mariasql

var inspect = require('util').inspect;
var Client = require('mariasql');

var client = new Client();
client.connect
(
	{
  		host: '127.0.0.1',
  		user: 'root',
  		password: 'Password42'
	}
);

client.on
(
	'connect', function() { console.log('Client connected'); }
).on
(
	'error', function(err) { console.log('Client error: ' + err); }
).on
(
	'close', function(hadError) { console.log('Client closed'); }
);

client.query('SHOW DATABASES').on
(
	'result', 
	function(result) 
	{
		result.on
		(
			'row', 
			function(row) { console.log('Result row: ' + inspect(row)); }
		).on
		(
			'error', 
			function(err) { console.log('Result error: ' + inspect(err)); }
		).on
		(
			'end', 
			function(info) { console.log('Result finished successfully'); }
		);
 	}
).on
(
	'end', 
	function() { console.log('Done with all results'); }
);

client.end();

7. In the same directory that contains the file “NodeJSMariaDBTest.js”, create a new text file named “Run.bat”, containing the text shown below.

node NodeJSMariaDBTest.js
pause

8. Execute the file “Run.bat”. A console window will appear, and a list of all the available databases in the MariaDB instance will be displayed.

UPDATE 2015/08/21 – A more object-oriented, callback-capable version of the program is included below.

var inspect = require("util").inspect;
var MariaSQLClient = require("mariasql");

// main
function main()
{
	var database = new Database
	(
		"127.0.0.1", // host
		"root", // username
		"Password42" // password
	);

	database.query
	(
		"SHOW DATABASES",
		databaseQueryComplete,
		null // thisForQuery
	);
}

function databaseQueryComplete(rowsRetrieved)
{
	console.log("Rows retrieved:");

	for (var i = 0; i < rowsRetrieved.length; i++)
	{
		var row = rowsRetrieved[i];
		console.log(row);
	}
}

// classes

function Database(host, username, password)
{
	this.client = new MariaSQLClient();
	this.client.connect
	(
		{
	  		host: host,
	  		user: username,
	  		password: password
		}
	);

	this.client.on
	(
		"connect", 
		this.handleEventClientConnect.bind(this)
	).on
	(
		"error", 
		this.handleEventClientError.bind(this)
	).on
	(
		"close",
		this.handleEventClientClose.bind(this)
	);
}
{
	Database.prototype.query = function(queryText, callback, thisForCallback)
	{
		this.client.query(queryText).on
		(
			"result", 
			this.handleEventQueryResult.bind(this, callback, thisForCallback)
		).on
		(
			"end", 
			this.handleEventQueryEnd.bind(this)
		);

		this.client.end();
	}

	// events

	Database.prototype.handleEventClientClose = function(hadError) 
	{ 
		console.log("Client closed."); 
	}

	Database.prototype.handleEventClientConnect = function() 
	{ 
		console.log("Client connected."); 
	}

	Database.prototype.handleEventClientError = function(error)
	{
		{ console.log("Client error: " + error); }
	}

	Database.prototype.handleEventQueryEnd = function() 
	{ 
		console.log("Done with all results."); 
	}

	Database.prototype.handleEventQueryResult = function
	(
		callback, thisForCallback, result
	) 
	{
		var rowsRetrieved = [];

		result.on
		(
			"row", 
			this.handleEventQueryResultRow.bind
			(
				this, 
				rowsRetrieved
			)
		).on
		(
			"error", 
			this.handleEventQueryResultError.bind(this)
		).on
		(
			"end", 
			this.handleEventQueryResultEnd.bind
			(
				this, rowsRetrieved, callback, thisForCallback
			)
		);
	}

	Database.prototype.handleEventQueryResultEnd = function
	(
		rowsRetrieved, callback, thisForCallback, info
	) 
	{ 
		console.log("Result finished successfully."); 
		callback.call(thisForCallback, rowsRetrieved);
	}

	Database.prototype.handleEventQueryResultError = function(error) 
	{ 
		console.log("Result error: " + inspect(error)); 
	}

	Database.prototype.handleEventQueryResultRow = function(rowsRetrieved, row) 
	{ 
		var rowAsString = inspect(row);
		rowsRetrieved.push(rowAsString);
	}
}

// run

main();
This entry was posted in Uncategorized and tagged , , , , , , . Bookmark the permalink.

2 Responses to Accessing MariaDB from JavaScript Using Node.js and Node-MariaSQL

  1. rg443 says:

    Reblogged this on rg443blog and commented:
    Node.js, MariaDB, Node-MariaSQL

  2. Pingback: A Simple Web Server in Node.js with a MariaDB Backend | This Could Be Better

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s