어떤 기능을 조립할 수 있는 형태로 만든 부분
fs.readFile
: 파일을 읽을 때 사용하는 메서드writeFile
: 파일을 저장할 때 사용하는 메서드Node.js v16.18.1 Documentation
JavaScript 코드 가장 상단에 require
구문을 이용하여 다른 파일을 불러오기
const fs = require('fs'); // 파일 시스템 모듈을 불러오기
const dns = require('dns'); // DNS 모듈을 불러오기
해당 프로그래밍 언어에서 공식적으로 제공하는 빌트인 모듈(built-in module)이 아닌 모든 외부 모듈
npm install
구문: 서드 파티 모듈 다운로드하기//서드 파티 모듈인 underscore 설치하기
npm install underscore
require
구문: npm을 이용해 설치한 서드 파티 모듈(3rd-party module)을 불러오기const _ = require('underscore'); // underscore 모듈 불러오기
fs.readFile(path[, options], callback)
fs.readFile
은 비동기적으로 파일 내용 전체를 읽음fs.readFile('/example/somefile', ..., ...)
// /example/somefile 파일을 'utf8'을 사용하여 읽습니다.
fs.readFile('/example/somefile', 'utf8', ...);
let options = {
encoding: 'utf8', // utf8 인코딩 방식으로 열기
flag: 'r' // 읽기 위해 엶
}
// /example/somefile 파일을 options을 활용해서 열기
fs.readFile('/etc/passwd', options, ...)
callback(err, data)
err
: Error 또는 AggregateError
data
: string 또는 Buffer
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
throw err; // 에러를 던짐
}
console.log(data); // 에러가 없으면 data를 콘솔창에 표시
});