DEV Community

Cover image for Learning Node.js in 30 Days with AI - Day 4
King Triton
King Triton

Posted on • Updated on

Learning Node.js in 30 Days with AI - Day 4

Today, I continued learning Node.js with the help of ChatGPT, and we focused on asynchronous programming. This is one of the most important concepts in Node.js, and I'm excited to have started mastering it.

Theory

In Node.js, asynchronous programming is crucial due to its non-blocking, event-driven architecture. This means that operations such as file reading, database queries, or network requests do not block the execution of other code while waiting for a result.

We explored three main ways to handle asynchronous operations:

  1. Callbacks: Functions passed as arguments to other functions, which are executed once an asynchronous operation completes.

    const fs = require('fs');
    
    fs.readFile('example.txt', 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log(data);
    });
    
  2. Promises: Objects representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises allow chaining and make the code more readable compared to nested callbacks.

    const fs = require('fs').promises;
    
    fs.readFile('example.txt', 'utf8')
        .then(data => {
            console.log(data);
        })
        .catch(err => {
            console.error(err);
        });
    
  3. Async/Await: Syntactic sugar built on top of Promises that allows writing asynchronous code in a synchronous manner.

    const fs = require('fs').promises;
    
    async function readFile() {
        try {
            const data = await fs.readFile('example.txt', 'utf8');
            console.log(data);
        } catch (err) {
            console.error(err);
        }
    }
    
    readFile();
    

Practical Task

Today, I practiced converting a callback-based function to a promise-based function.

Original code with callbacks:

const fs = require('fs');

function readFileCallback(path, callback) {
    fs.readFile(path, 'utf8', (err, data) => {
        if (err) {
            callback(err);
            return;
        }
        callback(null, data);
    });
}

readFileCallback('example.txt', (err, data) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log(data);
});
Enter fullscreen mode Exit fullscreen mode

Conversion to Promises:

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

function readFilePromise(path) {
    return fs.readFile(path, 'utf8');
}

readFilePromise('example.txt')
    .then(data => {
        console.log(data);
    })
    .catch(err => {
        console.error(err);
    });
Enter fullscreen mode Exit fullscreen mode

Independent Task

I also wrote an asynchronous function using async/await that reads the content of a file and logs it to the console. If an error occurs (e.g., file not found), it should catch the error and log it.

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

async function readFileAsync(path) {
    try {
        const data = await fs.readFile(path, 'utf8');
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}

readFileAsync('example.txt');
Enter fullscreen mode Exit fullscreen mode

Resources

All lessons created by ChatGPT can be found at: https://king-tri-ton.github.io/learn-nodejs

Top comments (0)