Thursday, July 4, 2024

Node.js - MySQL Connection Pool

In the post Node.js - Connect to MySQL Promise API we have seen how to connect to MySQL using Promise based API of mysql2 package. Using mysql2 package you can also create a connection pool.

By using a database connection pool, you can create a pool of connections that can be reused, that helps in reducing the time spent connecting to the MySQL server. When you need to connect to DB you take a connection from the pool and that connection is released again to the pool, rather than closing it, when you are done.

Creating MySQl connection pool

You can create a connection pool by using createPool() method.

import mysql from 'mysql2/promise';
const pool = mysql.createPool({
  host: 'localhost',
  user: 'USER_NAME',
  password: 'PASSWORD',
  database: 'node', 
  port: 3306
});

Replace USER_NAME and PASSWORD with your MySQL configured user name and password. Port number used is the default 3306 (if you are using default port even port number is optional) and it is connecting to DB named node which I have created in MySQL.

There are other settings also for which default is used if no value is provided.

import mysql from 'mysql2/promise';

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  database: 'test',
  waitForConnections: true,
  connectionLimit: 10,
  maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
  idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
  queueLimit: 0,
  enableKeepAlive: true,
  keepAliveInitialDelay: 0,
});

MYSQL2 Connection Pool with Promise Based API Example

Here is a complete example where connection pool is used to get a connection and execute queries.

Table used for the example-

CREATE TABLE `node`.`employee` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `join_date` DATE NOT NULL,
  `age` INT NULL,
  PRIMARY KEY (`id`));

util\database.js

This is the file where connection pool is created and pool object is exported so that it can be used in other files.

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'admin',
  database: 'node',
  waitForConnections: true, // this is default anyway
  connectionLimit: 10, // this is default anyway
});

module.exports = pool;

The pool does not create all connections upfront but creates them on demand until the connection limit is reached.

app.js

const pool = require('./util/database');

async function insertEmployee(empName, joinDate, age){
  const sql = "INSERT INTO EMPLOYEE (name, join_date, age) values (?, ?, ?)";
  const values = [empName, joinDate, age];
  try{
    const conn = await pool.getConnection();
    const [result, fields] = await conn.execute(sql, values);
    console.log(result);
    console.log(fields);
    conn.release();
  }catch(err){
    console.log(err);
  }
}

insertEmployee('Rajesh', '2023-06-17', 34);

Important points to note here-

  1. insertEmployee() function is a async function as we are using async/await (Promise based API) rather than callback based API.
  2. We are using await with pool.getConnection() method.
  3. By using array destructuring we get the returned values for result and fields.
  4. fields variable contains extra meta data about results, if available.
  5. result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  6. After the task, connection is released using conn.release() which means connection goes back to the pool.

On running the file-

>node app.js

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 1,
  info: '',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 0
}

undefined

In the above example connection is acquired manually from the pool and manually returned to the pool.

You can also use pool.query() and pool.execute() methods directly. When using these methods connection is automatically released when query resolves.

Here is one more function getEmployees() where pool.query() is used.

async function getEmployees(){
  const sql = "SELECT * FROM EMPLOYEE";
  try{
    const [result, fields] = await pool.query(sql);
    console.log(result);
  }catch(err){
    console.log(err);
  }
}

getEmployees();

On running the file app.js with getEmployee() method-

>node app.js
[
  {
    id: 1,
    name: 'Rajesh',
    join_date: 2023-06-16T18:30:00.000Z,
    age: 34
  }
]

That's all for this topic Node.js - MySQL Connection Pool. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Node.js - How to Connect to MySQL
  2. Writing a File in Node.js

You may also like-

  1. Node.js path.resolve() Method
  2. NodeJS Blocking Non-blocking Code
  3. Java Record Class With Examples
  4. Exception Propagation in Java Exception Handling
  5. Invoking Getters And Setters Using Reflection in Java
  6. React Virtual DOM
  7. Spring Transaction Management Example - @Transactional Annotation and JDBC

Node.js path.resolve() Method

In the post Node.js path.join() Method we saw how path.join() method can be used to join the path segments to form a final path. In Node.js path module there is also a path.resolve() method that is used to resolve path segments into an absolute path.

The given path segments are processed from right to left, with each subsequent path prepended until an absolute path is constructed. Method stops prepending more path segments as soon as an absolute path is formed.

After processing all the given path segments if an absolute path has not yet been generated, the current working directory is used to construct an absolute path.

If no path segments are passed, path.resolve() will return the absolute path of the current working directory.

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

path.resolve() method syntax

path.resolve([...paths])

...paths is a sequence of path segments of type string that are resolved into an absolute path.

Method returns a String representing an absolute path.

A TypeError is thrown if any of the arguments is not a string.

path.resolve() method Node.js examples

Suppose I have a Node.js app created under nodews directory with that context let's try to use path.resolve() method to see how absolute paths are formed. We'll also use path.join() with the same path segments to give an idea how path.resolve() differs from path.join() method.

1. Passing various path segments

const path = require('path');

console.log(__dirname);

const filePath = path.join("app", "views", "mypage.html");
console.log('path.join() output:', filePath);

const resolvePath = path.resolve("app", "views", "mypage.html");
console.log('path.resolve() output:', resolvePath);

Output

D:\NETJS\NodeJS\nodews
path.join() output: app\views\mypage.html
path.resolve() output: D:\NETJS\NodeJS\nodews\app\views\mypage.html

As you can see path.join() just adds the path segment and returns it whereas path.resolve() tries to construct an absolute path using passed path segments. Since it is not able to generate an absolute path after processing all given path segments, the current working directory is used to construct an absolute path.

2. Giving one of the path segments with separator.

const path = require('path');

console.log(__dirname);

const filePath = path.join("/app", "views", "mypage.html");
console.log('path.join() output:', filePath);

const resolvePath = path.resolve("/app", "views", "mypage.html");
console.log('path.resolve() output:', resolvePath);

Output

D:\NETJS\NodeJS\nodews
path.join() output: \app\views\mypage.html
path.resolve() output: D:\app\views\mypage.html

As you can see path.join() just adds the path segment and returns it whereas path.resolve() processes the path segments from right to left until an absolute path is constructed. Method is able to form an absolute path when it comes to '/app' path segments.

3. Having more path segments with separator.

const path = require('path');

console.log(__dirname);

const filePath = path.join("/app", "/views", "mypage.html");
console.log('path.join() output:', filePath);

const resolvePath = path.resolve("/app", "/views", "mypage.html");
console.log('path.resolve() output:', resolvePath);

Output

D:\NETJS\ NodeJS\nodews
path.join() output: \app\views\mypage.html
path.resolve() output: D:\views\mypage.html

4. Having separator in the rightmost path segment.

const path = require('path');

console.log(__dirname);

const filePath = path.join("/app", "/views", "/mypage.html");
console.log('path.join() output:', filePath);

const resolvePath = path.resolve("/app", "/views", "/mypage.html");
console.log('path.resolve() output:', resolvePath);

Output

D:\NETJS\NodeJS\nodews
path.join() output: \app\views\mypage.html
path.resolve() output: D:\mypage.html

5. Using '..' (one level up) as one of the path segments.

const path = require('path');

console.log(__dirname);

const filePath = path.join("/app", "/views", "..", "mypage.html");
console.log('path.join() output:', filePath);

const resolvePath = path.resolve("/app", "/views", "..", "mypage.html");
console.log('path.resolve() output:', resolvePath);

Output

D:\NETJS\NodeJS\nodews
path.join() output: \app\mypage.html
path.resolve() output: D:\mypage.html

Here path.resolve() will initially construct the absolute path as D:\views\..\mypage.html which is then normalized to D:\mypage.html

That's all for this topic Node.js path.resolve() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Node.js path.basename() Method With Examples
  2. __dirname and __filename in Node.js
  3. NodeJS Event Loop
  4. Node.js - Connect to MySQL Promise API

You may also like-

  1. Difference Between __dirname and process.cwd() in Node.js
  2. Reading a File in Node.js
  3. Node.js Event Driven Architecture
  4. Java ThreadLocal Class With Examples
  5. Why Class Name And File Name Should be Same in Java
  6. Running Dos/Windows Commands From Java Program
  7. Angular Pipes With Examples
  8. Spring Boot Event Driven Microservice With Kafka

Monday, July 1, 2024

Node.js path.join() Method

The path.join() method in Node.js Path module is used to join all given path segments together to form a single well formed path. While forming the path path.join() method takes care of the following.

  1. Uses the platform-specific separator as a delimiter. For example / on POSIX and either \ or / on Windows.
  2. Normalizes the resulting path. While normalizing following tasks are done.
    • Resolves '..' (parent directory or one level up) and '.' (current directory) segments.
    • When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and \ on Windows).
    • If the path is a zero-length string, '.' is returned, representing the current working directory.

path.join() method syntax

path.join([...paths])

...paths is a sequence of path segments of type string which are joined together to form a path.

Method returns a String representing the final path.

Throws TypeError if any of the path segments is not a string.

path.join() method Node.js examples

1. Joining various path segments

const path = require('path');

const filePath = path.join("app", "views", "mypage.html");
console.log(filePath);

Output

app/views/mypage.html

2. Normalizing path by removing any extra path separators.

const path = require('path');

const filePath = path.join("app", "/views", "//mypage.html");
console.log(filePath);

Output

app/views/mypage.html

3. Using with __dirname to get the path starting from the directory of currently executing file.

const path = require('path');

const filePath = path.join(__dirname, "views", "mypage.html");
console.log(filePath);

Output

D:\NETJS\NodeJS\nodews\views\mypage.html

Same code in Linux system

const path = require('path');

const filePath = path.join(__dirname, "views", "mypage.html");
console.log(filePath);

Output

/home/netjs/nodeapp/views/mypage.html

4. Using '..' path segment to go one level up. For example, if file is executing in directory D:\NETJS\NodeJS\nodews\views\mypage.html then the following code

const path = require('path');

const filePath = path.join(__dirname, "..", "views", "mypage.html");
console.log(filePath);
gives the output as
D:\NETJS\NodeJS\views\mypage.html

It is because the file where this code resides is in D:\NETJS\NodeJS\nodews and '..' path segment means going one level up meaning D:\NETJS\NodeJS

That's all for this topic Node.js path.join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Node.js path.basename() Method With Examples
  2. __dirname and __filename in Node.js
  3. NodeJS Blocking Non-blocking Code
  4. Node.js - How to Connect to MySQL

You may also like-

  1. Appending a File in Node.js
  2. Node.js REPL
  3. Creating HTTP server in Node.js
  4. Difference Between yield And sleep in Java Multi-Threading
  5. Compact Strings in Java
  6. Convert float to String in Java
  7. Directives in Angular
  8. Transaction Management in Spring