AI를 통해 며칠 만에 Node.js 배우기 - 4일차

PHPz
풀어 주다: 2024-08-29 11:31:32
원래의
242명이 탐색했습니다.

Learning Node.js in Days with AI - Day 4

오늘은 ChatGPT의 도움으로 Node.js를 계속 배우고 비동기 프로그래밍에 집중했습니다. 이는 Node.js의 가장 중요한 개념 중 하나이며, 이를 마스터하게 되어 기쁩니다.

이론

Node.js에서는 비차단 이벤트 기반 아키텍처로 인해 비동기 프로그래밍이 중요합니다. 이는 파일 읽기, 데이터베이스 쿼리 또는 네트워크 요청과 같은 작업이 결과를 기다리는 동안 다른 코드의 실행을 차단하지 않는다는 것을 의미합니다.

우리는 비동기 작업을 처리하는 세 가지 주요 방법을 살펴보았습니다.

  1. 콜백: 비동기 작업이 완료되면 실행되는 다른 함수에 인수로 전달되는 함수입니다.

    const fs = require('fs');
    
    fs.readFile('example.txt', 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log(data);
    });
    
    로그인 후 복사
  2. 약속: 비동기 작업의 최종 완료(또는 실패)와 결과 값을 나타내는 개체입니다. Promise는 연결을 허용하고 중첩된 콜백에 비해 코드를 더 읽기 쉽게 만듭니다.

    const fs = require('fs').promises;
    
    fs.readFile('example.txt', 'utf8')
        .then(data => {
            console.log(data);
        })
        .catch(err => {
            console.error(err);
        });
    
    로그인 후 복사
  3. 비동기/대기: Promise를 기반으로 구축된 구문 설탕으로 비동기 코드를 동기 방식으로 작성할 수 있습니다.

    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();
    
    로그인 후 복사

실무

오늘은 콜백 기반 함수를 Promise 기반 함수로 변환하는 연습을 해봤습니다.

콜백이 포함된 원본 코드:

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);
});
로그인 후 복사

약속으로의 전환:

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);
    });
로그인 후 복사

독립작업

또한 파일 내용을 읽고 이를 콘솔에 기록하는 async/await를 사용하여 비동기 함수를 작성했습니다. 오류가 발생하면(예: 파일을 찾을 수 없음) 오류를 포착하여 기록해야 합니다.

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');
로그인 후 복사

리소스

ChatGPT에서 만든 모든 강의는 https://king-tri-ton.github.io/learn-nodejs

에서 확인할 수 있습니다.

위 내용은 AI를 통해 며칠 만에 Node.js 배우기 - 4일차의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!