브라우저 환경과는 다르게 Node.js 환경은 로컬 컴퓨터에서 직접 실행되므로, 파일을 불러오거나 저장하는 등의 액션이 가능합니다. fs(File System) module 사용법을 잘 익힌다면 "파일 열기", "파일 저장하기" 등을 직접 구현할 수 있습니다. Node.js 에서는 파일을 읽는 비동기 함수를 제공합니다. 이를 통해 callback과 Promise 구현해 봅니다.
주어진 테스트를 전부 통과하세요.
npm run test:part-2 명령으로 테스트를 실행할 수 있습니다.
파일 이름에 표시된 번호 순서대로 진행해 주세요.
callBack ➡️ promiseConstructor ➡️ basicChaining ➡️ promiseAll ➡️ asyncAwait
part-2/01_callBack.js 파일을 구현하고, 테스트를 통과합니다. fs.readFile의 공식 API 문서, Node.js 공식 문서 가이드를 참고하세요.getDataFromFile 을 사용해서, 어떻게 작동되는지 직접 파악해 보세요.// part-2/01_callBack.js
const fs = require("fs");
const getDataFromFile = function (filePath, callback) {
// 구현하세요
};
// 다음 코드를 추가해 넣은 후, js 파일을 실행해보세요.
getDataFromFile("README.md", (err, data) => {
console.log(data);
});
module.exports = {
getDataFromFile,
};
[코드] part-2/01_callBack.js 파일
node part-2/01_callback.js
[커맨드] part-2/01_callBack.js 파일을 실행합니다.
part-2/02_promiseConstructor.js 파일을 구현하고, 테스트를 통과합니다.
callback 이라는 파라미터(인자) 대신, Promise의 reject, resolve 함수를 이용하세요.
part-2/03_basicChaining.js은, 앞서 작성한 getDataFromFilePromise를 이용해서 풀어야 합니다.
fs 모듈을 직접 사용하는 것이 아닙니다.getDataFromFilePromise을 이용해, files/user1.json 파일과 files/user2.json 파일을 불러오고, 두 파일을 합쳐서 최종적으로 두 객체가 담긴 배열을 만드는 것이 목표입니다.user1Path 및 user2Path를 이용하세요. then이 어떠한 파라미터를 전달받는지에 대한 이해가 있어야 합니다.then의 리턴이 무엇을 의미하는지 이해하고 있어야 합니다.문자열이므로, JSON.parse 를 사용해야 문제를 해결할 수 있을 것입니다.part-2/04_promiseAll.js은, 마찬가지로 readAllUsersChaining과 정확히 같은 결과를 리턴합니다.
Promise.all을 반드시 사용해서 풀어야 합니다.part-2/05_asyncAwait.js은, 앞서 진행한 readAllUsersChaining, readAllUsers과 같은 결과를 리턴합니다.async 및 await 키워드를 사용해서 해결해야 합니다.Node.js 에서 경로를 다룰 때, dirname과 path module은 매우 유용합니다. 다음 링크는 dirname의 사용 방법에 대해 설명합니다. How to use __dirname in Node.js
The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument is null or undefined.
출처: node.js API
https://nodejs.org/api/fs.html#fs_callback_example