728x90
https://opentutorials.org/course/3332/21028
생활코딩님의 Node.js강의를 참고하였습니다.
1.동기(Synchronous)
동기 방식에서는 코드가 작성된 순서대로 실행됩니다. 각 작업이 완료될 때까지 다음 작업이 시작되지 않습니다. 따라서, 특정 작업이 오래 걸리면 그 작업이 완료될 때까지 프로그램의 실행이 멈추고, 이후의 코드는 실행되지 않습니다.
const fs = require('fs');
// 동기적 파일 읽기
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
// 이 줄은 파일 읽기가 끝난 후에 실행됨
console.log('This will be printed after reading the file.');
2.비동기(Asynchronous)
비동기 방식에서는 작업을 시작한 후, 그 작업이 완료되기를 기다리지 않고 다음 코드를 즉시 실행합니다. 비동기 작업이 완료되면, 콜백 함수, 프라미스(Promise), 또는 async/await와 같은 메커니즘을 통해 결과를 처리합니다.
const fs = require('fs');
// 비동기적 파일 읽기
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 이 줄은 파일 읽기를 시작한 직후에 실행됨
console.log('This will be printed before the file is completely read.');
728x90
'BackEnd > Node.js' 카테고리의 다른 글
[Node.js] PM2 (0) | 2024.08.16 |
---|---|
[Node.js] 모듈화 (0) | 2024.08.15 |
[Node.js] fs.readdir 파일 목록 읽기,글목록 출력하기 (0) | 2024.08.15 |