Home  >  Article  >  Web Front-end  >  Learning Node.js in Days with AI - Day 4

Learning Node.js in Days with AI - Day 4

PHPz
PHPzOriginal
2024-08-29 11:31:32320browse

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

The above is the detailed content of Learning Node.js in Days with AI - Day 4. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn