My experience with NodeJS and MariaDB on Android through Termux

The first thing I did was check the official documentation, Getting Started With the Node.js Connector

I modified my server.js code and tested and first error I encountered was, "Error: (conn=20, no: 1698, SQLState: 28000) Access denied for user 'u0_a270'@'localhost'"

At some point in troubleshooting I also got this error, "ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/data/data/com.termux/files/usr/tmp/mysqld.sock'"

Eventually I figured out that the problem was with the mariadb user that was created on install and how no password is required for mysql in Termux. So I just created a new user for my dev work as follows

MariaDB [db1] > CREATE USER 'user1'@localhost IDENTIFIED BY 'password1';

MariaDB [db1] > GRANT ALL PRIVILEGES ON *.* TO 'user1'@localhost IDENTIFIED BY 'password1';

Then my testing nodejs code as follows

const mariadb = require('mariadb');
const pool = mariadb.createPool({
     host: 'localhost',
     user:'user1',
     password: 'password1',
     database: 'db1',
     connectionLimit: 5
});

var http = require('http');

http.createServer(async function (req, res) {
  res.write('Device listing : ');
 
  rows = await queryDB();
 
  rows.forEach(function (row) {
  res.write(row.id + ' ' + row.name + '; '); });
 
  res.end();
}).listen(3000);

async function queryDB() {
  let conn;
  try {
conn = await pool.getConnection();
rows = await conn.query("SELECT * from devices");
  } catch (err) {
throw err;
  } finally {
if (conn) { conn.end(); return rows; }
  }
}

Man I was so happy to see this work after troubleshooting for a few hours. Hopefully this helps someone trying to get started with the same thing.

MariaDB example

Comments

Popular posts from this blog

How does the sun set?

What is the story behind the broken kite?

Surfing

What is a beautiful word?

What is love?