fs 모듈

김범주·2022년 3월 11일
0

Code Review

목록 보기
5/15

callback.js

const getDataFromFile = function (filePath, callback) {
  // TODO: fs.readFile을 이용해 작성합니다
  fs.readFile(filePath, 'utf-8', (err, data) => {
    if (err) {
      callback(err, null)
    }
    else {
      callback(null, data)
    }
  })
};

promiseConstructor.js

const getDataFromFilePromise = filePath => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
  // TODO: Promise 및 fs.readFile을 이용해 작성합니다.
};

basicChaining.js

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)
  .then((user1) => {
    return getDataFromFilePromise(user2Path).then((user2) => {
      return '[' + user1 + ',' + user2 + ']'
    })
  })
  .then((ans) => JSON.parse(ans))
}

promiseAll.js

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

const readAllUsers = () => {
  // TODO: Promise.all을 이용해 작성합니다
  return Promise.all([getDataFromFilePromise(user1Path), getDataFromFilePromise(user2Path)])
  .then(([user1, user2]) => {
    return '[' + user1 + ',' + user2 + ']'
  })
  .then((ans) => {
    return JSON.parse(ans)
  })
}

asyncAwait.js

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

const readAllUsersAsyncAwait = async () => {
  // TODO: async/await 키워드를 이용해 작성합니다
  let ans = []
  const user1 = await getDataFromFilePromise(user1Path)
  const user2 = await getDataFromFilePromise(user2Path)
  ans.push(JSON.parse(user1), JSON.parse(user2))
  return ans
}
profile
개발꿈나무

0개의 댓글