Part 2 - fs 모듈 실습

Jelkov Ahn·2021년 10월 14일
2

JS/NODE 비동기

목록 보기
5/6
post-thumbnail

01_callBack.JS

fs.readlink(path[, options], callback)#

path <string> | <Buffer> | <URL>
options <string> | <Object>
encoding <string> Default: 'utf8'
callback <Function>
err <Error>
linkString <string> | <Buffer>
  • 문제
const fs = require("fs");

const getDataFromFile = function (filePath, callback) {
  // TODO: fs.readFile을 이용해 작성합니다
};

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

module.exports = {
  getDataFromFile
};
  • 코드
const fs = require("fs"); 
//파일 시스템 모듈을 불러옴. 그래야지 fs.readFile등의 메소드를 사용할 수 있음.

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

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

module.exports = {
  getDataFromFile //타 파일에서 함수를 사용할 수 있도록 export
};

02_promiseConstructor.JS

  • 문제
    • callback 이라는 파라미터(인자) 대신 Promise 객체의 reject, resolve 함수를 이용한다.
const fs = require("fs");

const getDataFromFilePromise = filePath => {
  // return new Promise()
  // TODO: Promise 및 fs.readFile을 이용해 작성합니다.
};

// getDataFromFilePromise('README.md').then(data => console.log(data));

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

getDataFromFilePromise('README.md')
  .then(data => console.log(data)); 

module.exports = {
  getDataFromFilePromise
};

03_basicChaining.JS

  • 문제
    • Promise 형태로 리턴
    • getDataFromFilePromise 함수를 이용해 files/user1.json과 files/user2.json 파일을 불러와서 합친 뒤 두 객체가 담긴 배열을 만든다.
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으로 연결하여 작성합니다
}

// readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}
  • 코드(1)
    • 파일 읽기의 결과가 문자열이므로 JSON.parse 메소드를 이용해 JSON포맷의 문자열을 javaScript object로 변환한다.
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));
};

// readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}
  • (X)되긴 되지만 추천하지 않는 코드(2)
    밖에다가 선언해서 사용하는 것은 추천하지 않는다.(Side effect)

    • 순수함수의 개념에 대해서 좀 이해 해야한다.
      순수함수 : 한함수에서 일어난일이 밖에 영향을 미치는 경우 영향을 미칠수가 있다!!
const path = require('path');
//이번엔 path 모듈을 불러옴으로써 아래 path.join 메소드를 사용하였다.
const { getDataFromFilePromise } = require('./02_promiseConstructor'); //2번 파일의 함수를 긁어와 재사용할 수 있게 한다.

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json'); //You can use __dirname to check on which directories your files live -->부가 자료에서 이 내용을 찾았다. 객체가 들어있는 각 json 파일의 파일 path를 나타내는 것이라고 이해하고 넘어갔다.

// HINT: getDataFromFilePromise(user1Path) 맟 getDataFromFilePromise(user2Path) 를 이용해 작성합니다
const readAllUsersChaining = () => {
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
  
  let result = [];
  return getDataFromFilePromise(user1Path) //
  .then((value)=>{ //value={user1정보} 가 전달인자로 들어감
    let parsed1 = JSON.parse(value) //파싱시키고
    result.push(parsed1) //result에다가 푸시. result = [{user1정보}]인 상태.
    return getDataFromFilePromise(user2Path) //또 실행시켜서 user2 정보를 전달인자로 넘김
  })
  .then((value)=>{
    let parsed2 = JSON.parse(value)
    result.push(parsed2)//result에다가 푸시. result = [{user1정보}, {user2정보}]인 상태.
    return result;
  })
}

readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}

알아둬야 할점 : 비동기적인 코드로 되어 있지만, 동기적으로 작동하는 것을 확인 할 수 있다.

04_promiseAll.JS

  • 문제
    • 3번째 파일과 같은 결과를 리턴해야 하지만 Promise.all을 사용한다.
    • Promise all
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을 이용해 작성합니다
}

// readAllUsers()

module.exports = {
  readAllUsers
}
  • 코드(1)
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 = () => {
  const user1 = getDataFromFilePromise(user1Path)
  const user2 = getDataFromFilePromise(user2Path)

  return Promise.all([user1, user2]).then((result)=>{
    return result.map((e)=> JSON.parse(e));
  })
  // TODO: Promise.all을 이용해 작성합니다
}

readAllUsers()

module.exports = {
  readAllUsers
}
  • 코드(2)
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([	//	Promise.all에 
    getDataFromFilePromise(user1Path),	// 경로 두 개를 담은 배열을 인자로 받는다.
    getDataFromFilePromise(user2Path)
  ]).then(([user1, user2]) => {	// 각각의 결과값을 담은 배열이 들어오면
      return '[' + user1 + ',' + user2 +']' // 하나로 합쳐준다.
  })
  .then((result) => JSON.parse(result))
}

알아둬야 할점: 동기적으로 동시에 작동을 하게 된다.

05_asyncAwait.JS

async 어쩔수 없이 동기적으로 사용해야 할때 ~ 이게 간결하다고 생각이 들때 !! 사용한다.

  • 문제
    • await를 사용해서 풀어라.
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 = () => {
  // TODO: async/await 키워드를 이용해 작성합니다
}

// readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}
  • 코드(1)
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 키워드를 이용해 작성합니다
  const user1 = await getDataFromFilePromise(user1Path)
  const user2 = await getDataFromFilePromise(user2Path)
  return [JSON.parse(user1), JSON.parse(user2)]
}

readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}
  • 코드(2)
const path = require('path');
const { deflateRawSync } = require('zlib');
const { getDataFromFilePromise } = require('./02_promiseConstructor');

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

const readAllUsersAsyncAwait = async() => {
  let user1 = await getDataFromFilePromise(user1Path);
  let user2 = await getDataFromFilePromise(user2Path);
  
  let result = '[' + user1 + ',' + user2 +']' 
  let json = JSON.parse(result);
  return json;
}
readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}
profile
끝까지 ... 가면 된다.

0개의 댓글