CallBack Function – one good way to explain callback in Sync and Async way.

In this post, let’s use the Callback to read a file. Naturally, reading a file is not instantaneous; it is necessary some time to read them, and all will happen in an async way. Our script can continue while the file is read and will call back when finished. All will be clear in the examples.

Let’s create a file called callback.js. On it, we will use two node modules:

File System and Path modules.

The “file system” node module will allow us to read a file, and the “path” node module, provides a way of working with directories and file paths.

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

Let’s create a data file. Let’s call it data.txt:

line 1
line 2
line 3

Creating a pathway to the file:

const fs = require("fs");
const path = require("path");
const pathWay = path.join(__dirname, "data.txt");
console.log(pathWay);
// OutPut:
// /home/flavio/blog_posts/callback/data.txt

Using the “file system,” we have two functions to read a file: readFileSync and readFile. For now, we will use readFile because it will need a callback.

The readFile function receives the parameters: path, options(not used in this example) and callback. We will pass another two parameters on the callback: err and data(that will be our data.txt file). If you are using VSCode, with the cursor on top of the readFile, you can understand better reading the popup message.

You can see that the callback parameters must pass another parameter, err and data. Let’s create a function for it. In the sequence, we call the function readFile:

showContent function.

const fs = require("fs");
const path = require("path");
const pathWay = path.join(__dirname, "data.txt");
// console.log(pathWay);
function showContent(err, content) {
  if (err) console.log("Error");
  else console.log(content.toString());
}
fs.readFile(pathWay, {}, showContent);
// OutPut:
// line 1
// line 2
// line 3

Notice that we use (content.toString()) without it. The function delivers us an unreadable Buffer, you can take off and test.

Now let’s prove that the readFile function is using the async callback:

const fs = require("fs");
const path = require("path");
const pathWay = path.join(__dirname, "data.txt");
// console.log(pathWay);
function showContent(err, content) {
  if (err) console.log("Error");
  else console.log(content.toString());
}
console.log("Start...")
fs.readFile(pathWay, {}, showContent);
console.log("Finish the script and callback")
// OutPut:
// Start...
// Finish the script and callback 
// line 1
// line 2
// line 3

First, we can see that the Start message and following the readFile function executed the instruction in an async way. We conclude it because only after showing the Finish message we could see the data.txt content.

Conclusion.

To conclude. Let’s use the readFileSync to read our file in the Sync way. We will use the console.log to see the execution flow:

const fs = require("fs");
const path = require("path");
const pathWay = path.join(__dirname, "data.txt");
function showContent(err, content) {
  if (err) console.log("Error");
  else console.log(content.toString());
}
console.log("Start Async...");
fs.readFile(pathWay, {}, showContent);
console.log("Continue...");
console.log("Start Sync...");
const content = fs.readFileSync(pathWay);
console.log(content.toString());
console.log("Finish Sync and Callback the Async...");
// OutPut:
// Start Async...
// Continue...
// Start Sync...
// line 1
// line 2
// line 3
// Finish Sync and Callback the Async...
// line 1
// line 2
// line 3

Here you can see. The readFile function executes on Async way, continuing the script. The readFileSync function starts and shows the data.txt content, and only when finishing Callback to show Async content.

Thank you for reading.



2 responses to “CallBack Function – one good way to explain callback in Sync and Async way.”

  1. Nice post. I learn something totally new and challenging on websites I stumbleupon on a daily basis. It will always be interesting to read through content from other writers and use something from their websites.

  2. Good site! I truly love how it is simple on my eyes and the data are well written. I’m wondering how I could be notified whenever a new post has been made. I have subscribed to your feed which must do the trick! Have a great day!

Leave a Reply

Your email address will not be published. Required fields are marked *