fs모듈

안윤경·2022년 7월 28일
0

과제

목록 보기
11/20

fs모듈과제

1.

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

});
};
  • readfile의 function은 콜백함수를 전달!->function안에 (err, data)를 넣어준다.

2.

const fs = require("fs");

const getDataFromFilePromise = filePath => {
  // return new Promise()
  // TODO: Promise 및 fs.readFile을 이용해 작성합니다.
  return new Promise((resolve , reject)=>{
    fs.readFile(filePath, "utf8", (err, data)=>{
      if(err){
        reject(err)
      }else{
        resolve(data)
      }
    });
  }
)}
  • promise를 사용하기 위해서는 return값과 함께 new Promise를 써줘야한다
  • 위와 다른점이라고 하면 위에서는 콜백함수로 받은 err를 여기서는 reject와 resolve로 받아줘야한다.

3.

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 readAllUsersChaining = () => {
  return getDataFromFilePromise(user1Path)
    .then(user1 => {
      return getDataFromFilePromise(user2Path).then(user2 => {
        return '[' + user1 + ',' + user2 + ']';
      });
    })
    .then(text => JSON.parse(text))
}
  • return getDataFromFilePromise(user1Path)
    .then(console.log)를 찍으면 user1.json객체가 나오게 된다
    then안에 임의의 인자 user1을 넣고 바로 user2path를 리턴을 해준다 이후
    .then으로 배열안에 넣어 리턴을 해주는데 이때 주의점!

    1. user1의 then을 배열의 return이 끝날때까지 닫으면 안된다는 것이다
      만약 닫게되면 user1의 값을 쓸 수 없기에 조심해야함!

4.

	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 = () => {
  return Promise.all([
    getDataFromFilePromise(user1Path),
    getDataFromFilePromise(user2Path)
  ])
    .then(([user1, user2]) => {
      return '[' + user1 + ',' + user2 + ']';
    })
    .then(text => JSON.parse(text))
}
  • promiseall은()안에 배열로 받기 때문에 배열처럼 쓸 수 있다
    밑에 then부분은 map을써서 풀어도 된다

.then((data)=>{
      return data.map((el)=>JSON.parse(el));
  })
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() => {
  // TODO: async/await 키워드를 이용해 작성합니다
  let a = await getDataFromFilePromise(user1Path);
  let b = await getDataFromFilePromise(user2Path);
  return [JSON.parse(a), JSON.parse(b)]
}

헷갈린점

1.then이라는 매서드안에 왜 인자를 넣는가에 대하여
2.callback함수에 err,data넣는이유

profile
프론트엔드 개발자 안윤경입니다

0개의 댓글