"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Learning Node.js in Days with AI - Day 4

Learning Node.js in Days with AI - Day 4

Published on 2024-11-05
Browse:312

Learning Node.js in 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);
});

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

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

Resources

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

Release Statement This article is reproduced at: https://dev.to/king_triton/learning-nodejs-in-30-days-with-ai-day-4-3o69?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3