Showing posts with label NodeJS. Show all posts
Showing posts with label NodeJS. Show all posts

Monday, August 26, 2024

Node.js MySQL Delete Example

In the post Node.js MySQL Update Example we saw examples of updating records in a table using Node.js and MySQL. In this post we'll see examples of deleting records from table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


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`));

Node.js delete record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

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

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

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to delete Employee record from employee table in MySQL DB.

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

async function deleteEmployee(id){
  // TODO Verify if emp with the same id exists or not.. 
  // For that select query to get by id can be used

  const sql = "DELETE FROM EMPLOYEE where id = ?";
  const values = [id];
    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);
    }
}

deleteEmployee(1);

Important points to note here-

  • deleteEmployee() function is an async function as we are using async/await (Promise based API) rather than callback-based API.
  • We are using await with pool.getConnection() method.
  • deleteEmployee() function takes one argument where it expects an id for the employee to be deleted.
  • Delete query is created as a parameterized query, where id is passed later. By having this kind of prepared statement makes our code more generic to be used with any id and also gives better performance.
  • By using array destructuring we get the returned values for result and fields.
  • fields variable contains extra meta data about results, if available.
  • result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  • 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: 0,
  info: '',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 0
}

undefined

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


Related Topics

  1. Node.js MySQL Insert Example
  2. Node.js MySQL Select Statement Example
  3. Node.js - MySQL Connection Pool

You may also like-

  1. Node.js path.resolve() Method
  2. NodeJS Event Loop
  3. Node.js Event Driven Architecture
  4. How to Setup a Node.js Project
  5. Custom Async Validator in Angular Reactive Form
  6. Pre-defined Functional Interfaces in Java
  7. Java Program to Convert a File to Byte Array
  8. JavaScript let and const With Examples

Saturday, August 24, 2024

Node.js MySQL Update Example

In the post Node.js MySQL Insert Example we have seen how to do an insert in MySQL DB from Node.js application. In this post we'll see examples of updating records in a table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Refer Node.js - MySQL Connection Pool to get more information about using MySQL Connection Pool with Node.js

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


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`));

Node.js update record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

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

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

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to update Employee record in MySQL.

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

async function updateEmployee(emp){
  // Verify if emp with the same id exists or not
  // For that select query to get by id can be used

  const sql = "UPDATE EMPLOYEE set name = ?, join_date = ?, age = ? where id = ?";
  const values = [emp.name, emp.joinDate, emp.age, emp.id];
    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);
    }
}

//calling function with employee object
updateEmployee({name:'Ishan', joinDate:'2024-04-23', age:28, id:1})

Important points to note here-

  1. updateEmployee() function is an 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. updateEmployee() function takes one argument where it expects an employee object to be passed.
  4. Using that object, appropriate values are passed to the prepared statement to update a record.
  5. By using array destructuring we get the returned values for result and fields.
  6. fields variable contains extra meta data about results, if available.
  7. result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  8. 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: 0,
  info: 'Rows matched: 1  Changed: 1  Warnings: 0',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 1
}

Undefined

If you want to get the number of rows which are updated you can get it using result.affectedRows from the result object.

You can check the DB to see the updated values.

Node.js MySQL Update

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


Related Topics

  1. Node.js MySQL Select Statement Example
  2. Node.js MySQL Delete Example
  3. Node.js - Connect to MySQL Promise API

You may also like-

  1. Node.js path.basename() Method With Examples
  2. __dirname and __filename in Node.js
  3. Appending a File in Node.js
  4. Creating HTTP server in Node.js
  5. Service in Angular With Examples
  6. Java Stream - count() With Examples
  7. Why main Method static in Java
  8. Named Tuple in Python

Tuesday, July 16, 2024

Node.js MySQL Select Statement Example

In this post we'll see examples of Select statement using Node.js and MySQL to fetch data from DB. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Refer Node.js - MySQL Connection Pool to get more information about using MySQL Connection Pool with Node.js

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


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`));

Id is auto incremented so we don't need to send that data from our code.

Node.js MySQL Select statement example

In this example all the records are fetched from the Employee table.

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

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

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

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to select all the records from the Employee table.

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

async function getEmployees(){
  const sql = "SELECT * FROM EMPLOYEE";
  try{
    const conn = await pool.getConnection();
    const [results, fields] = await conn.query(sql);
    console.log(results); // results contains rows returned by server
    console.log(fields);
    conn.release();
  }catch(err){
    console.log(err);
  }
}

getEmployees(30);

Important points to note here-

  1. getEmployees () 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 results and fields.
  4. results contains rows returned by server.
  5. fields variable contains extra meta data about results, if available.
  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
[
  {
    id: 1,
    name: 'Ishan',
    join_date: 2024-03-23T18:30:00.000Z,
    age: 28
  },
  {
    id: 2,
    name: 'Rajesh',
    join_date: 2023-06-16T18:30:00.000Z,
    age: 34
  }
]
[
  `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` VARCHAR(45),
  `join_date` DATE(10) NOT NULL,
  `age` INT
]

Select with where condition example

In this example we'll have a condition using Where clause, only those records are selected that fulfil the condition. For the condition, parameterized query is used.

app.js

In this file let's create a function to select data from the Employee table in MySQL based on the age condition.

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

async function getEmployeesByAge(age){
  const sql = "SELECT * FROM EMPLOYEE where age >?";
  const values = [age];
  try{
    const conn = await pool.getConnection();
    const [result, fields] = await conn.execute(sql, values);
    console.log(result); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
    conn.release(); // connection sent back to pool
  }catch(err){
    console.log(err);
  }
}

getEmployeesByAge(30);

On running it

>node app.js
[
  {
    id: 2,
    name: 'Rajesh',
    join_date: 2023-06-16T18:30:00.000Z,
    age: 34
  }
]
[
  `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` VARCHAR(45),
  `join_date` DATE(10) NOT NULL,
  `age` INT
]

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


Related Topics

  1. Node.js MySQL Insert Example
  2. Node.js MySQL Update Example
  3. Node.js - Connect to MySQL Promise API

You may also like-

  1. How to Setup a Node.js Project
  2. Node.js Event Driven Architecture
  3. Node.js path.basename() Method With Examples
  4. Writing a File in Node.js
  5. Fail-Fast Vs Fail-Safe Iterator in Java
  6. Java Stream - Convert Stream to List
  7. Switch Expressions in Java 12
  8. Custom Pipe in Angular With Example

Monday, July 15, 2024

Node.js MySQL Insert Example

In this post we'll see examples of inserting records into table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Refer Node.js - MySQL Connection Pool to get more information about using MySQL Connection Pool with Node.js

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


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`));

Id is auto incremented so we don't need to send that data from our code.

Node.js insert record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

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

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

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to insert data into the Employee table in MySQL.

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

async function insertEmployee(){
  const sql = "INSERT INTO EMPLOYEE (name, join_date, age) values ('Ishan', '2023-11-22', 31)";
  try{
    const conn = await pool.getConnection();
    const [result, fields] = await conn.query(sql);
    console.log(result);
    console.log(fields);
    conn.release();
  }catch(err){
    console.log(err);
  }
}

// call the function
insertEmployee();

Important points to note here-

  • insertEmployee() function is a async function as we are using async/await (Promise based API) rather than callback based API.
  • We are using await with pool.getConnection() method.
  • By using array destructuring we get the returned values for result and fields.
  • fields variable contains extra meta data about results, if available.
  • result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  • 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

If you want to get the number of rows inserted you can get it using result.affectedRows and to get the id of the inserted row you can use result.insertId

Using parameterized Insert query

In the above example problem is that insert query will insert the same record as the data is hardcoded. To make it more generic you can use a parameterized query with the placeholders for the values that are passed later.

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);
  }
}

// call the function
insertEmployee('Ishan', '2024-03-24', 28);
insertEmployee('Rajesh', '2023-06-17', 34);

Important points to note here-

  1. Prepared statement is used now where placeholders are used to pass values later.
  2. Values are passed in an array which is also passed along with the query.
  3. conn.execute() is used here rather than conn.query() as execute helper prepares and queries the statement.

Inserting multiple records - Node.js and MySQL

In the above example parameterized query is used which is definitely a step forward to using hardcoded data. If you have multiple records to be inserted simultaneously then you can use single question mark '?' which represents multiple rows of data coming from an array.

app.js

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

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

const records = [
  ['Ishan', '2024-03-24', 28], 
  ['Rajesh', '2023-06-17', 34]
]
// call the function
insertEmployee(records);

On running it

>node app.js

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

Undefined

As you can see affected rows count is 2.

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


Related Topics

  1. Node.js MySQL Update Example
  2. Node.js MySQL Delete Example
  3. Node.js - How to Connect to MySQL
  4. Node.js MySQL Select Statement Example

You may also like-

  1. Difference Between __dirname and process.cwd() in Node.js
  2. Node.js path.join() Method
  3. Reading a File in Node.js
  4. Setting Wild Card Route in Angular
  5. Difference Between Comparable and Comparator in Java
  6. Java is a Strongly Typed Language
  7. How to Create Password Protected Zip File in Java

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

Tuesday, June 25, 2024

Node.js - Connect to MySQL Promise API

In the post Node.js - How to Connect to MySQL we have seen how to connect to MySQL using mysql2 package. There callback-based API was used to connect and to run query but mysql2 package also has a Promise based API where you don't need to provide callback functions instead you can use aync/await to make your code more readable.

Creating connection from NodeJS app

Once mysql2 is installed you can use that driver to connect to MySQL and execute queries through your NodeJS app.

For creating a connection you can use createConnection() method, with Promise also you can use one of the following ways to create a connections.

1. Using createConnection(connectionUri)

const mysql = require('mysql2/promise');
try {
  const connection = await mysql.createConnection(
    'mysql://USER_NAME:PASSWORD@localhost:3306/node'
  );
} catch (err) {
  console.log(err);
}

Replace USER_NAME and PASSWORD with your MySQL configured user name and password. Port number used is the default 3306 and it is connecting to DB named node which I have created in MySQL.

2. Using createConnection(config)

You can also call createConnection() by passing a config object which has the required connection options. This is the preferred way to create a connection.

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

try {
  const connection = await mysql.createConnection({
  host: 'localhost',
  user: 'USER_NAME',
  password: 'PASSWORD',
  database: 'node', 
  port: 3306
  });
} catch (err) {
  console.log(err);
}

Using MYSQL2 Promise Based API Query Example

Here is a complete example where INSERT statement is used to insert a record into employee table which is created in node schema.

Employee Table

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`));

We'll use a separate file to keep DB properties which can then be passed to createConnection() method.

util\config.js

const config = {
  dbproperties: {
    host: 'localhost',
    user: 'root',
    password: 'admin',
    database: 'node', 
    port: 3306
  }
}

module.exports = config;

app.js

const mysql = require('mysql2/promise');
const config = require('./util/config');

async function insertEmployee(){
  const conn = await mysql.createConnection(config.dbproperties);
  const sql = "INSERT INTO EMPLOYEE (name, join_date, age) values ('Rajesh', '2022-06-17', 37)";
  try{
    const [result, fields] = await conn.execute(sql);
    console.log(result);
    console.log(fields);
  }catch(err){
    console.log(err);
  }
}

insertEmployee();

Important points to note here-

  1. insertEmployee() function is a async function as we are using async/await now rather than callback based API.
  2. We are using await with createConnection() method.
  3. By using array destructuring we get the returned values for result and fields.
  4. fields contains extra meta data about results, if available.
  5. result contains a ResultSetHeader object, which provides details about the operation executed by the server.

On running it

>node app.js

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

From the values displayed you can observe that result.insertId will give you the ID of the inserted record and result.affectedRows will give you the number of rows that are inserted.

Using parameterized query

Above example of insert query has very limited use as values are hardcoded and it can only insert that particular record. In order to make it more generic we can use a parameterized query with placeholders for the values that are passed later.

const mysql = require('mysql2/promise');
const config = require('./util/config');

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

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

Important points to note here-

  1. insertEmployee() function is a async function and takes 3 parameters for the three fields that are to be inserted into the table. We don’t need to insert id as that will be automatically incremented by DB.
  2. Insert query is parameterized with three placeholders for three values. These values are passed as an array.
    const values = [empName, joinDate, age];
    
  3. In connection.execute() method both query (String) and values (array) are passed. Using the query with placeholders and values parameters, execute() method prepares and queries the statement.

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


Related Topics

  1. How to Setup a Node.js Project
  2. Writing a File in Node.js

You may also like-

  1. Difference Between __dirname and process.cwd() in Node.js
  2. Binary Search Program in Java
  3. How to Create Immutable Class in Java
  4. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
  5. Spring Web Reactive Framework - Spring WebFlux Tutorial
  6. Angular Disable Button Example

Node.js - How to Connect to MySQL

In this tutorial we'll see how to connect to MySQL database from Node.js application.

Prerequisite for this tutorial is that you already have MySQL installed in your system.

Installing MySQL driver

To connect to MySQL from NodeJS you need to install MySQL driver for Node.js. We'll use MySQL2 driver which can be installed using the following command.

npm install --save mysql2

Creating connection from NodeJS app

Once mysql2 is installed you can use that driver to connect to MySQL and execute queries through your NodeJS app.

For creating a connection you can use createConnection() method, you can either pass URI or use config object with connection options.

1. Using createConnection(connectionUri)

// Get the client
const mysql = require('mysql2');

const conn = mysql.createConnection(
  'mysql://USER_NAME:PASSWORD@localhost:3306/node'
);

Replace USER_NAME and PASSWORD with your MySQL configured user name and password. Port number used is the default 3306 and it is connecting to DB named node which I have created in MySQL.

2. Using createConnection(config)

You can also call createConnection() by passing a config object which has the required connection options. This is the preferred way to create a connection.

// Get the client
const mysql = require('mysql2');

//create connection to database
const conn = mysql.createConnection({
  host: 'localhost',
  user: 'USER_NAME',
  password: 'PASSWORD',
  database: 'node', 
  port: 3306
})

Once you have the connection object you can use that to call connection() method to explicitly establish a connection with MySQL database.

conn.connect((err) => {
  if(err){
    console.error(err);
    return;
  }
  console.log("connected to DB");
})

Check this post- Node.js - Connect to MySQL Promise API to connect to MySQL database from Node.js using Promise based API provided by mysql2 driver.

Executing query using connection

Here is a complete example where INSERT statement is used to insert a record into employee table which is created in node schema.

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`));

database.js

// Get the client
const mysql = require('mysql2');

//create connection to database
const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'admin',
  database: 'node', 
  port: 3306
})

conn.connect((err) => {
  if(err){
    console.error(err);
    return;
  }
  console.log("connected to DB");
  const sql = "INSERT INTO EMPLOYEE (name, join_date, age) values ('Rajesh', '2022-06-17', 34)";
  // now run query
  conn.query(sql, (err, result, fields) => {
    if(err){
        console.error(err);
        return;
    }
    console.log(result);
    console.log(fields);
  });
})

On running it

>node database.js

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

undefined

Here note that result and fields provide the following information.

  • result: Contains a ResultSetHeader object, which provides details about the operation executed by the server.
  • fields: Contains extra meta data about the operation, if available

You can also implicitly establish a connection by directly invoking a query, no need to explicitly establish a connection using connection() method.

Following code also connects to DB and inserts a record though connect() method is omitted.

// Get the client
const mysql = require('mysql2');

//create connection to database
const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'admin',
  database: 'node', 
  port: 3306
})

const sql = "INSERT INTO EMPLOYEE (name, join_date, age) values ('Rajesh1', '2022-06-17', 37)";
conn.query(sql, (err, result, fields) => {
  if(err){
      console.error(err);
      return;
  }
  console.log(result);
  console.log(fields);
});

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


Related Topics

  1. Node.js - Connect to MySQL Promise API
  2. Node.js - MySQL Connection Pool
  3. Node.js MySQL Insert Example
  4. NodeJS Blocking Non-blocking Code
  5. Node.js REPL

You may also like-

  1. NodeJS NPM Package Manager
  2. Creating HTTP server in Node.js
  3. Node.js path.basename() Method With Examples
  4. Java Collections Interview Questions And Answers
  5. How to Loop or Iterate an Arraylist in Java
  6. Spring Web MVC Tutorial
  7. How to Create a Custom Observable in Angular
  8. Convert String to float in Python

Thursday, June 20, 2024

Difference Between __dirname and process.cwd() in Node.js

In this article we'll see the difference between __dirname and process.cwd() method in Node.js.

__dirname in Node.js

__dirname in Node.js is a local variable which stores the absolute path of the directory where the currently executing file (module) resides.

In Node.js, each file is treated as a module and before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:

(function(exports, require, module, __filename, __dirname) {
  // Module code actually lives in here
}); 

That's why convenience variables __dirname and __filename, containing the module's absolute filename and directory path are local variables which are specific to the module.

process.cwd() in Node.js

The process.cwd() method returns the current working directory of the Node.js process (not the module).

With process.cwd() working directory depends on from where the node process starts whereas with __dirname working directory depends on the file which is currently executing.

__dirname Vs process.cwd()

Let's try to clear the difference between __dirname and process.cwd() using few examples.

Suppose we have a file pathdemos/pathdemo.js in project root directory.

pathdemos/pathdemo.js

function test(){
    console.log('in function test()');
    console.log('__dirname:', __dirname);

    console.log('process.cwd():', process.cwd())
}

test();

module.exports = {test};

On running this file-

D:\NETJS\NodeJS\nodews\pathdemos>node pathdemo.js

in function test()
__dirname: D:\NETJS\NetJS_2017\NodeJS\nodews\pathdemos
process.cwd(): D:\NETJS\NetJS_2017\NodeJS\nodews\pathdemos

As you can see node invokes pathdemo.js so process.cwd() returns the working directory as path to pathdemo.js. Currently executing file is also pathdemo.js so __dirname also returns the current directory as path to pathdemo.js.

Let's try to execute test() function from some other file. So, we'll remove the test() method execution from pathdemo.js and export the function.

pathdemos/pathdemo.js

function test(){
    console.log('in function test()');
    console.log('__dirname:', __dirname);

    console.log('process.cwd():', process.cwd())
}

module.exports = {test};

There is another file app.js residing in project root directory.

app.js

const p = require('./pathdemos/pathdemo');
p.test();

Check the output by running app.js file.

D:\NETJS\NodeJS\nodews>node app.js

in function test()
__dirname: D:\NETJS\NetJS_2017\NodeJS\nodews\pathdemos
process.cwd(): D:\NETJS\NetJS_2017\NodeJS\nodews

As you see now __dirname is path to pathdemo.js because test() function executes in pathdemo.js where as process.cwd() gives path to project root directory because node invokes app.js so that is the running process.

That's all for this topic Difference Between __dirname and process.cwd() in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Node.js Tutorial Page


Related Topics

  1. Node.js REPL
  2. How to Setup a Node.js Project
  3. NodeJS Blocking Non-blocking Code
  4. Node.js path.basename() Method With Examples
  5. Appending a File in Node.js

You may also like-

  1. Synchronization in Java - Synchronized Method And Block
  2. Marker Interface in Java
  3. How to Create PDF From XML Using Apache FOP
  4. BeanPostProcessor in Spring Framework
  5. Angular One-Way Data Binding Using String Interpolation

Thursday, June 13, 2024

Node.js path.basename() Method With Examples

Path module in Node.js provides many utility methods to work with file and directory paths. In this article we'll see how to use path.basename() method which returns the last portion of a path that means you can extract the filename from the full path using this method.

Syntax of path.basename()

path.basename(path, suffix)
  • path- This is the file path from which last portion has to be extracted. This is a required parameter.
  • suffix- This is an optional parameter. If the filename ends with the given suffix (extension) then the extension is removed.

This method returns a string which is the extracted filename from the given path. A TypeError is thrown if path is not a string or if suffix is given and is not a string.

The default operation of the path.basename() method varies based on the operating system on which a Node.js application is running. Which means method will take care of both paths '/' (Posix) and '\' (Windows).

path.basename() example in Node.js

basename.js

const path = require('path'); 
console.log('filePath- ', __filename);
const fileName = path.basename(__filename); 
console.log(fileName);

Output

filePath-  D:\NETJS\ NodeJS\nodews\pathdemos\basename.js
basename.js

Here __filename variable is used to get the absolute path of the currently executing file. From that filename is extracted using path.basename() method.

path.basename() with suffix argument

If you pass file extension as the second argument then the extension is removed from the file name.

const path = require('path'); 

console.log('filePath- ', __filename);
console.log('File Extension- ', path.extname(__filename))

const fileName = path.basename(__filename, path.extname(__filename)); 
console.log(fileName);

Output

filePath-  D:\NETJS\NodeJS\nodews\pathdemos\basename.js
File Extension-  .js
basename

Note that path.extname() method is used here to get the extension of the file rather than hardcoding the file extension.

If you have Unix style file paths then also path.basename() method works without any problem.

const path = require('path'); 
const filePath = '/home/netjstech/nodejs/pathdemos/basename.js'
const fileName = path.basename(filePath); 
console.log(fileName);

Output

basename.js

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


Related Topics

  1. Node.js path.join() Method
  2. Node.js path.resolve() Method
  3. Writing a File in Node.js
  4. NodeJS Blocking Non-blocking Code
  5. Appending a File in Node.js

You may also like-

  1. Node.js REPL
  2. Creating HTTP server in Node.js
  3. Setting Wild Card Route in Angular
  4. Custom Pipe in Angular With Example
  5. Java trim(), strip() - Removing Spaces From String
  6. Java Phaser With Examples
  7. Difference Between Abstract Class And Interface in Java

__dirname and __filename in Node.js

In this article we'll see what are __dirname and __filename variables in Node.js and how to use them.

__dirname in Node.js

__dirname in Node.js is a convenience variable which stores the absolute path of the directory where the currently executing file (module) resides.

__dirname examples

Suppose project structure is as given below.

myapp
|   app.js
|   package-lock.json
|   package.json  
+---bin 
+---controllers
|       product.js     
+---node_modules         
+---public
|   +---docs      
|   +---images
|   +---javascripts
|   +---stylesheets           
+---routes
|       index.js
|       users.js    
\---views
        error.ejs
        index.ejs

In the app.js if we have the following line of code

console.log('Directory path- ' + __dirname);

then on running the app.js file output is

Directory path- D:\NETJS\NodeJS\nodews\myapp

Which is the absolute path of the directory where app.js file resides.

You can use __dirname in conjunction with path.join() to create paths relative to current file path. For example, if you need to read a file named hello.txt which is inside /public/docs as per the given project structure then you can construct the path using __dirname as given below-

const filePath = path.join(__dirname, "/public/docs/", "hello.txt");
console.log(filePath);
fs.readFile(filePath,'utf8', (err, data) => {
  if(err){
    console.log('Error while reading file');
  }else{
    console.log(data);
  }
});

Output for the filePath is-
D:\NETJS\NodeJS\nodews\myapp\public\docs\hello.txt

__filename in Node.js

__filename in Node.js is a convenience variable which stores the current module file's absolute path.

__filename examples

If we use the same project structure as already mentioned above then having the following lines in app.js

console.log('File Name- ' + __filename);
console.log('Directory path- ' + __dirname);
Gives us the following output
File Name- D:\NETJS\NodeJS\nodews\myapp\app.js
Directory path- D:\NETJS\NodeJS\nodews\myapp

If you want just the file name not the full path then wrap __filename in path.basename() method.

console.log('File Name- ' + path.basename(__filename));

Output

File Name- app.js

That's all for this topic __dirname and __filename in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. Introduction to Node.js
  2. Difference Between __dirname and process.cwd() in Node.js
  3. Node.js REPL
  4. Node.js Event Driven Architecture
  5. NodeJS Blocking Non-blocking Code

You may also like-

  1. Appending a File in Node.js
  2. How to Pass Command Line Arguments in Eclipse
  3. String in Java Tutorial
  4. Angular Custom Property Binding Using @Input Decorator
  5. Spring MVC Dropdown Example Using Select, Option And Options Tag

Friday, June 7, 2024

Appending a File in Node.js

In the post Writing a File in Node.js we saw how to use methods of fs module to write to a file. When you use writeFile() method it rewrites the file if file already exists. If you need to append to a file then fs module has methods to do that too.

How to append to a file in Node.js

In the fs module there are both synchronous and asynchronous methods to append to a file. Description is as given below.

  1. fs.appendFile()- This method asynchronously appends data to a file, creating the file if it does not yet exist. A callback function is provided which is called when the file append operation is completed.
  2. fs.appendFileSync- This method synchronously appends data to a file, creating the file if it does not yet exist.
  3. fsPromises.appendFile()- This method is in the fs.promises API which asynchronously appends data to a file, creating the file if it does not yet exist. Method returns a Promise object which is resolved with undefined upon success.

Using fs.appendFile()

Syntax of fs.appendFile() method is as given below.

fs.appendFile(path, data, options, callback)

The four parameters are described below-

  1. file- Path to the file where content has to be written or file descriptor (a number returned by opening the file using the open() method).
  2. data- Content to be written to the file. It can be of type string or Buffer.
  3. options- It specifies optional parameters that can be provided with write operation. Type can be either string or object. Optional parameters are described below-
    • encoding- A string value specifying the encoding of the file. Default is 'utf8'
    • mode- An integer value specifying the file mode. Default is 0o666 which means both read and write.
    • flag- Flag used in append operation. Default flag is 'a' which means open file for appending. The file is created if it does not exist.
    • flush- If true, the underlying file descriptor is flushed prior to closing it. Default value is false.
  4. callback- A function that is called when the file operation completes. Takes one argument err which denotes the error that can be thrown if append operation fails.

fs.appendFile () Example

const fs = require('fs');
var os = require("os");
const path = require('path');

const content = 'This is a line added to the file' + os.EOL;
fs.appendFile(path.join(__dirname, 'Hello.txt'), content, (err) => {
    if(err){
        console.error(err);
    }else {
        console.log("Append operation completed");
    }
})

Here os.EOL const of the 'os' module is used to add new line at the end.

Using fs.appendFileSync()

Syntax of fs.appendFileSync() method is as given below

fs.appendFileSync(path, data, options)

Description of parameters is similar to fs.appendFile()

fs.appendFileSync() Example

const fs = require('fs');
var os = require("os");
const path = require('path');

const content = 'This is a line added to the file' + os.EOL;
fs.appendFileSync(path.join(__dirname, 'Hello.txt'), content);
console.log("Append operation completed");

Using fsPromises.appendFile()

Syntax of fsPromises.appendFile() method is as given below

fsPromises.appendFile(path, data, options)

Description of parameters is similar to fs.appendFile() method as given above.

fsPromises.appendFile() example

const fs = require('fs');
const fspromises = fs.promises;
var os = require("os");
const path = require('path');

// uses async/await
const appendFile =  async (filePath) => {
    try{
        const content = 'This is a line added to the file' + os.EOL;
        await fspromises.appendFile(filePath, content);
        console.log("Append operation completed");
    } catch(error){
        console.error(err);
    }
}

// function call
appendFile(path.join(__dirname, 'Hello.txt'));

That's all for this topic Appending a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading a File in Node.js
  2. NodeJS Event Loop
  3. NodeJS Blocking Non-blocking Code
  4. Node.js REPL
  5. NodeJS NPM Package Manager

You may also like-

  1. Matrix Addition Java Program
  2. String in Java Tutorial
  3. JavaScript Arrow Function With Examples
  4. Angular Two-Way Data Binding With Examples
  5. Passing Arguments to getBean() Method in Spring

Tuesday, June 4, 2024

Writing a File in Node.js

In the post Reading a File in Node.js we saw how to use methods of fs module to read a file. In this post we'll see how to write a file in Node.js using the methods of the fs module.

How to write to a file in Node.js

In the fs module there are two methods to write to a file.

fs.writeFile()- This functions writes the file content in a non-blocking, asynchronous manner, replacing the file if it already exists. A callback function is provided which is called when the file write operation is completed.

fs.writeFileSync()- It is the synchronous function for writing content to a file which means it blocks while the write operation is in progress. The function returns undefined.

Apart from these two methods there is also a writeFile() function in the fs.promises API which asynchronously writes to a file and returns a Promise object which is resolved with no arguments upon success. Thus, you don't need a callback function.

Using fs.writeFile()

Syntax of fs.writeFile() method is as given below.

fs.writeFile( file, data, options, callback )
The four parameters are described below-
  1. file- Path to the file where content has to be written or file descriptor (a number returned by opening the file using the open() method).
  2. data- Content to be written to the file. It can be of type string, Buffer, TypedArray, DataView.
  3. options- It specifies optional parameters that can be provided with write operation. Type can be either string or object. Optional parameters are described below-
    • encoding- A string value specifying the encoding of the file. Default is 'utf8'
    • mode- An integer value specifying the file mode. Default is 0o666 which means both read and write.
    • flag- Flag used in write operation. Default flag is 'w' which means open file for writing, file is created if it doesn't exist or truncated if it exists.
    • flush- If all data is successfully written to the file, and flush is true, fs.fsync() is used to flush the data. Default value is false.
    • signal- Allows aborting an in-progress writeFile
  4. callback- A function that is called when the file operation completes. Takes one argument err which denotes the error that can be thrown if write operation fails.

fs.writeFile () Example

const fs = require('fs');
const path = require('path');

const content = 'Hello World from NodeJS!!';

fs.writeFile(path.join(__dirname, 'Hello.txt'), content, (err)=>{
    if(err){
        console.error('Error while writing to a file', err);
        return;
    }
});

If you want to give optional parameters then you can pass them as shown below-

const fs = require('fs');
const path = require('path');

const content = 'Hello World from NodeJS!!';

fs.writeFile(path.join(__dirname, 'Hello.txt'), content,  {
    encoding: "utf8",
    flag: "w",
    mode: 0o666
  }, (err)=>{
    if(err){
        console.error('Error while writing to a file', err);
        return;
    }
    console.log('File written Successfully');
});

Using fs.writeFileSync()

Syntax of fs.writeFileSync() method is as given below

fs.writeFileSync(file, data, options)

Description of parameters is similar to fs.writeFile()

fs.writeFileSync() Example

const fs = require('fs');
const path = require('path');

const content = 'Hello World from NodeJS!!';

try {
    fs.writeFileSync(path.join(__dirname, 'Hello.txt'), content);
    console.log('File written Successfully');
} catch (err) {
    console.error(err);
}

Using fsPromises.WriteFile()

Syntax of fsPromises.writeFile() method is as given below.

fsPromises.writeFile(file, data, options)

Description of parameters is similar to fs.writeFile() method as given above.

fsPromises.WriteFile() Example

const fs = require('fs');
const fsPromises = fs.promises;
const path = require('path');

async function writeFile(filePath) {
    try {
        const content = 'Hello World from NodeJS';
        await fsPromises.writeFile(filePath, content);
    } catch (err) {
        console.log(err);
    }
}

That's all for this topic Writing a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Appending a File in Node.js
  2. NodeJS Blocking Non-blocking Code
  3. Node.js REPL
  4. NodeJS NPM Package Manager
  5. Creating HTTP server in Node.js

You may also like-

  1. Difference Between HashMap And ConcurrentHashMap in Java
  2. ConcurrentSkipListMap in Java With Examples
  3. JSX in React
  4. Ternary Operator in Python
  5. Dependency Injection in Spring Framework
  6. Spring Integration With Quartz Scheduler

Monday, June 3, 2024

Reading a File in Node.js

The fs module in Node.js provides functions to work with the file system. Using fs module functions you can create file, read file, write to a file, append to a file, delete a file and do many other I/O tasks. In this article we'll see how to read a file in Node.js using methods of fs module.

How to read file in Node.js

In the fs module there are two methods to read a file.

fs.readFile()- This functions reads the file content in a non-blocking, asynchronous manner. A callback function is provided which is called when the file read operation is completed.

fs.readFileSync()- It is the synchronous version of fs.readFile() which means it is a blocking function. Function returns the contents of the file.

Apart from these two methods there is also a readFile() function in the fs.promises API which asynchronously reads the entire contents of a file and returns a Promise object which is resolved with the contents of the file. Thus, you don't need a callback function.

Using fs.readFile()

Syntax of fs.readFile() method is as given below

fs.readFile(file[, options], callback)

The three parameters are described below-

  1. file- This is the filename or file descriptor
  2. options- The optional options argument can be a string specifying an encoding (for example ‘utf8’), or an object with an encoding property specifying the character encoding and a flag with default as 'r' which indicates open file for reading. If both values are passed as an object then it will be like this {encoding: 'utf8', flag: 'r'}.
  3. callback function- A function that is called when the file operation completes. The callback function is passed two arguments (err, data).
    • err- Encapsulates the error, if any, while reading the file.
    • data- Contents of the file.

fs.readFile () Example

const fs = require('fs');
const path = require('path');

fs.readFile(path.join(__dirname, 'Hello.txt'), 'utf8', (err, data)=>{
    if(err){
        console.error('Error while reading file', err);
        return;
    }
    console.log(data);     
});

On running this example file, it should display the content of the passed file on the console.

Using fs.readFileSync()

Syntax of fs.readFileSync() method is as given below

fs.readFile(file[, options])

Description of parameters is same as in readFile() method.

fs.readFileSync() Example

const fs = require('fs');
const path = require('path');

const data = fs.readFileSync(path.join(__dirname, 'Hello.txt'), {encoding: 'utf8', flag: 'r'})
console.log(data);

Using fsPromises.readFile()

Syntax of fsPromises.readFile() method is as given below

fsPromises.readFile(file, options)

The parameters are described below-

  1. file- This is the filename or file descriptor
  2. options- The optional options argument can be a string specifying an encoding (for example ‘utf8’), or an object with an encoding property specifying the character encoding and a flag with default as 'r' which indicates open file for reading. If both values are passed as an object then it will be like this {encoding: 'utf8', flag: 'r'}.

This method returns a Promise so async/await can be used to make the code more readable.

fsPromises.readFile() Example

const fs = require('fs');
const fsPromises = fs.promises;
const path = require('path');

async function readFile(filePath) {
  try {
    const data = await fsPromises.readFile(filePath, { encoding: 'utf8' });
    console.log(data);
  } catch (err) {
    console.log(err);
  }
}

readFile(path.join(__dirname, 'Hello.txt'));

That's all for this topic Reading a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Writing a File in Node.js
  2. NodeJS Event Loop
  3. Node.js Event Driven Architecture
  4. NodeJS Blocking Non-blocking Code

You may also like-

  1. Creating HTTP server in Node.js
  2. How to Setup a Node.js Project
  3. How to Add Bootstrap to Angular Application
  4. Angular Pipes With Examples
  5. JavaScript Rest Parameter
  6. Find All Permutations of a Given String Java Program
  7. pass Statement in Python
  8. Spring Boot Microservice Example Using FeignClient

Friday, May 31, 2024

NodeJS Blocking Non-blocking Code

If you are doing programming from some time, you would have definitely heard the terms blocking and non-blocking or synchronous and asynchronous. NodeJS, which uses event-driven architecture, is also capable of performing non-blocking operations even though JavaScript is single-threaded thanks to the event loop in NodeJS.

What is Blocking code

If your code is executing synchronously that means it is executing line by line if there is a function call, control waits for function execution to finish. Which means execution of any further operation is blocked until the current operation completes.

In terms of Node.js, blocking code means the execution of additional JavaScript in the Node.js process is blocked until a non-JavaScript operation completes.

For example, if you are reading a file synchronously then the actual operation of reading the file content (non-JavaScript operation) blocks any other operation until reading the file completes.

Node.js blocking code example

In the 'fs' module there is a function readFileSync() that reads the file synchronously. Using that let's see how any other operation is blocked.

In the code there is a function readFileBlocking() which takes file path as parameter and then call fs.readFileSync() with that file to read the file synchronously. Content of the file is also logged to the console.

The function readFileBlocking() is called twice to read files Hello.txt and message.txt which reside in the project root directory.

const fs = require('fs');
const path = require('path');

const readFileBlocking = (filePath) => {
    console.log('Started reading ' + filePath);
    const data = fs.readFileSync(filePath, {encoding:'utf8'});
    console.log(data);
    console.log('Finished reading ' + filePath);
}

readFileBlocking(path.join(__dirname, 'Hello.txt'));
readFileBlocking(path.join(__dirname, 'message.txt'));
console.log('Waiting for file to be read....');

On running this code output is as given below for my project structure and the content I have in the two files.

Started reading D:\NETJS\NodeJS\nodews\Hello.txt
Hello from nodeJS
Finished reading D:\NETJS\NodeJS\nodews \Hello.txt
Started reading D:\NETJS\NodeJS\nodews \message.txt
This is a message from NodeJS
Finished reading D:\NETJS\NodeJS\nodews\message.txt
Waiting for file to be read....

Thing to note here is that reading of second file starts only after finishing the read operation for the first file, until then it is blocked. The message 'Waiting for file to be read....' is also displayed at the end after finishing the I/O operations. Actually this message will make more sense with the asynchronous operation here it should be changed to

console.log('File operations completed....');

What is non-blocking code

If your code is executing asynchronously that means it may not follow the convention of executing code line by line.

With non-blocking code If there is a function call, control doesn't wait for function execution to finish. It moves on to the next operation.

There must be a mechanism so that control is notified once the operation in progress finishes and control can come back to the finished operation to do any further processing like returning any data, use data in any other logic and so on.

In terms of Node.js non-blocking code means the execution of additional JavaScript in the Node.js process is not blocked until a non-JavaScript operation completes. There is a callback function which executes for any further processing once the non-JavaScript operation completes. For example, if you are reading a file asynchronously then the actual operation of reading the file content (non-JavaScript operation) doesn't block any other operation until reading the file completes.

Node.js non-blocking code example

In the 'fs' module there is a function readFile() that reads the file asynchronously.

In the code there is a function readFileNonBlocking() which takes file path as parameter and then call fs.readFile() with that file to read the file asynchronously. Content of the file is also logged to the console.

The function readFileNonBlocking() is called twice to read files Hello.txt and message.txt which reside in the project root directory.

const fs = require('fs');
const path = require('path');

const readFileNonBlocking = (filePath) => {
    console.log('Started reading ' + filePath);
    fs.readFile(filePath, 'utf8', (err, data) => {
        if(err){
            console.error('Error while reading file', err);
            return;
        }
        console.log(data); 
        console.log('Finished reading ' + filePath);       
    });
}

readFileNonBlocking(path.join(__dirname, 'Hello.txt'));
readFileNonBlocking(path.join(__dirname, 'message.txt'));
console.log('Waiting for file to be read....');

On running this code output is as given below for my project structure and the content I have in the two files.

Started reading D:\NETJS\NodeJS\nodews\Hello.txt
Started reading D:\NETJS\NodeJS\nodews\message.txt
Waiting for file to be read....
Hello from nodeJS
Finished reading D:\NETJS\NodeJS\nodews\Hello.txt
This is a message from NodeJS
Finished reading D:\NETJS\NodeJS\nodews\message.txt

From the output you can notice that operation is not getting blocked at fs.readFile() while the file is getting read control moves on to the next operation which also happens to be another file read operation so the control moves on to the next operation while the other file is getting read. That's why message 'Waiting for file to be read....' is displayed first.

Once the file read operation completes, callback function is called which display the file content.

You can compare the output of this example to the output of the blocking example to get better clarity.

That's all for this topic NodeJS Blocking Non-blocking Code. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Introduction to Node.js
  2. Node.js REPL
  3. Creating HTTP server in Node.js
  4. How to Setup a Node.js Project
  5. NodeJS NPM Package Manager

You may also like-

  1. Reading a File in Node.js
  2. JavaScript Rest Parameter
  3. Angular Event Binding With Examples
  4. NgNonBindable Directive in Angular
  5. Array in Java With Examples
  6. Fix Scanner.nextLine() Skipping Input After Another next Methods
  7. Difference Between @Controller And @RestController Annotations in Spring
  8. Python First Program - Hello World