2 minute read

2022.11.23

💡 오늘의 JavaScript 공부

▶️ -fs 모듈 개요

브라우저 환경과는 다르게 Node.js 환경은 로컬 컴퓨터에서 직접 실행되므로, 파일을 불러오거나 저장하는 등의 액션이 가능하다. File System module 사용법을 잘 익힌다면 ‘파일열기’, ‘파일 저장하기’등을 직접 구현할 수 있다.

📌callBack.js
const fs = require('fs')	// fs 모듈을 사용하겠다. 

const getDataFromFile = function (filePath, callback) {
  // TODO: fs.readFile을 이용해 작성합니다
  // fs 모듈을 이용해서 filePath라는 파일을 읽을 것이고 'utf8로 인코딩', 파일을 읽은 후 호출하는 콜백함수
  fs.readFile(filePath,'utf8',function(err,data){   
    if(err){ //만약 파일을 읽어오는데 실패했으면 
      callback(err, null); // err를 출력하고 data는 null
    }else{  // 그게 아니라면 
      callback(null,data) // err는 없고 data를 출력해라 
    }
  })
};

getDataFromFile('README.md', (err, data) => console.log(data));

module.exports = {
  getDataFromFile
};
📌 promiseConstructor.js
const fs = require("fs");

const getDataFromFilePromise = filePath => {
  // return new Promise()
  // TODO: Promise 및 fs.readFile을 이용해 작성합니다.
  // ! callback대신 Promise의 resolve, reject 함수를 이용해라
  return new Promise(function(resolve,reject){
    fs.readFile(filePath,'utf8',function(err,data){
      if(err){
        reject(err)
      }else{
        resolve(data)
      }
    })
  })
};
  • callback 대신 Promise 함수를 사용하라고 했으니까 new Promise를 호출해서 비동기 함수를 동기화 시킨다.
  • 그 다음은 위의 callback.js의 의사코드와 같음
📌 basicChaining.js
  • fs 모듈을 직접 사용하는 것이 아닙니다.
  • getDataFromFilePromise를 이용해, ‘files/user1.json’ 파일과 ‘files/user2.json’ 파일을 불러오고, 두 파일을 합쳐서 최종적으로 두 객체가 담긴 배열을 만드는 것이 목표입니다.
  • 파일 경로를 찾을 때, user1Path 및 user2Path를 이용하세요.
  • 파일 읽기의 결과가 문자열이므로, JSON.parse 를 사용해야 문제를 해결할 수 있습니다.
const { get } = require('http');
const path = require('path');
const { getDataFromFilePromise } = require('./02_promiseConstructor');

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');

// HINT: getDataFromFilePromise(user1Path) 및 getDataFromFilePromise(user2Path)를 이용해 작성합니다
const readAllUsersChaining = () => {
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
  return getDataFromFilePromise(user1Path)         // ! user1Path 파일 받아오기
  .then((user1Value) => JSON.parse(user1Value))    // ! 파일 읽기의 결과가 문자열이므로, JSON.parse 를 사용
  .then(user1 => {  // ! 파싱된 자료를 user1에 할당 
    return getDataFromFilePromise(user2Path)  // ! 그 뒤 user2Path 파일 받아오기
    .then((user2Value) => JSON.parse(user2Value)) // ! 파싱해주고
    .then(user2 => { 
      return [user1, user2]  // ! 두 객체가 담긴 배열을 만들기
    })
  })
}
📌 promiseAll.js
  • 위의 readAllUsersChaining과 정확히 같은 결과를 리턴합니다.
  • Promise.all을 반드시 사용해서 풀어야 합니다.
// Promise.all 은 처음봐서 찾아보았다. 
// MDN Promise.all 사용법
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]
const path = require('path');
const { getDataFromFilePromise } = require('./02_promiseConstructor');

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');

const readAllUsers = () => {
  // TODO: Promise.all을 이용해 작성합니다
  const user1 = getDataFromFilePromise(user1Path); // user1에 user1Path 파일을 불러와서 할당
  const user2 = getDataFromFilePromise(user2Path); // user2에 user2Path 파일을 불러와서 할당 
  return Promise.all([user1,user2]).then((value) => {
    return value.map((el) => JSON.parse(el)) // ! 두 데이터를 하나로 묶고 
    // 1대1 데이터 map 활용해서 파싱 
  })
}
📌 asyncAwait.js
// 위와 같은 결과를 리턴 
const path = require('path');
const { getDataFromFilePromise } = require('./02_promiseConstructor');

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');

const readAllUsersAsyncAwait = async() => {    // ! await 쓸거라 async 호출?
  // TODO: async/await 키워드를 이용해 작성합니다
  const user1 = await getDataFromFilePromise(user1Path); // ! user1path 받아오고
  const user2 = await getDataFromFilePromise(user2Path); // ! user2path 받아오고
  return [JSON.parse(user1),JSON.parse(user2)] // ! readAllUsers와 같은 결과를 리턴합니다.
}                                              // ! JSON.parse써서 같은 배열로 묶어주란 얘기

이번 과제는 의사코드를 많이 적어서 이해를 도왔고 처음부터 다시 하는 수고를 덜어 시간을 많이 단축할 수 있었다.

( 이후 실시간 세션 Reference Code를 통해 블로그 내용 보강 예정 )

Comments