node js 모듈

Creating the dots·2021년 7월 27일
0

Javascript

목록 보기
20/24

모듈이 뭐야?

건축으로부터 비롯된 모듈이라는 단어는, 어떤 기능을 조립할 수 있는 형태로 만든 부분이다. fs(File System) 모듈은, PC의 파일을 생성하거나 삭제하거나 읽거나 쓸 수 있게 도와준다.

Node.js 내장 모듈 이용하기

const fs = require('fs'); // 파일 시스템 모듈을 불러옵니다
const dns = require('dns'); // DNS 모듈을 불러옵니다
// 이제 fs.readFile 메소드 등을 사용할 수 있습니다

third party 모듈 이용하기

npm install underscore
const _ = require('underscore')
// 이제 underscore 모듈의 메소드를 사용할 수 있습니다.

fs 모듈 사용법

fs.readFile(path[, options], callback)

  • path

    • string || Buffer || URL || integer
  • options

    • string
    fs.readFile('/desktop/section2','utf8',...)
    • Object
    const options = {
      encoding: 'utf8', // UTF-8이라는 인코딩 방식으로 엽니다
      flag: 'r' // 읽기 위해 엽니다
    }
    fs.readFile('/desktop/section2',options,...)
  • callback

    • Function
      함수는 매개변수로 err과 data(file의 내용)를 입력받고, err가 있다면 throw error를 하고, data에는 문자열 또는 Buffer라는 객체가 전달된다. options에서 string으로 encoding을 작성한 경우, data에 문자열이 전달되고, 그렇지 않은 경우 data에 Buffer객체가 전달된다.

직접해보기

//readme.txt
//저를 읽어주세요

//readFile.js
const fs = require('fs');
fs.readFile('./readme.txt', (err,data)=>{
  if(err){
    throw err;
  }
  console.log(data);
  console.log(data.toString());
});

//<Buffer ec a0 80 eb a5 bc 20 ec 9d bd ec 96 b4 ec a3 bc ec 84 b8 ec 9a 94 2e>
//저를 읽어주세요
  • Buffer가 출력되는 경우
    readFile의 두번째 매개변수를 'utf8'로 값을 전달하지 않으면 data는 Buffer의 형식으로 출력되므로 문자열의 형태로 출력하고 싶다면, 두번째 매개변수로 'utf8'을 전달하거나 data.toString()을 해주면 된다.
profile
어제보다 나은 오늘을 만드는 중

0개의 댓글