logo

노드 JS fs.writeFile() 메서드

fs.writeFile() 메서드 지정된 데이터를 파일에 비동기적으로 쓰는 데 사용됩니다. 기본적으로 파일이 있으면 대체됩니다. 'options' 매개변수를 사용하여 메소드의 기능을 수정할 수 있습니다.

통사론:



fs.writeFile( file, data, options, callback )>

매개변수:

이 메서드는 위에서 언급하고 아래에 설명된 대로 네 가지 매개 변수를 허용합니다.

  • 파일: 이는 작성해야 하는 파일의 경로를 나타내는 문자열, 버퍼, URL 또는 파일 설명 정수입니다. 파일 설명자를 사용하면 fs.write() 메서드와 유사하게 동작합니다.
  • 데이터: 파일에 기록될 문자열, Buffer, TypedArray 또는 DataView입니다.
  • 옵션: 출력에 영향을 주는 선택적 매개변수를 지정하는 데 사용할 수 있는 문자열 또는 개체입니다. 여기에는 세 가지 선택적 매개변수가 있습니다.
    • 부호화: 파일의 인코딩을 지정하는 문자열 값입니다. 기본값은 'utf8'입니다.
    • 방법: 파일 모드를 지정하는 정수값입니다. 기본값은 0o666입니다.
    • 깃발: 파일에 쓰는 동안 사용되는 플래그를 지정하는 문자열 값입니다. 기본값은 'w'입니다.
  • 콜백: 메소드가 실행될 때 호출되는 함수입니다.
    • 오류: 작업이 실패하면 발생하는 오류입니다.

Node JS 애플리케이션을 생성하는 단계:

1 단계: 노드 프로젝트 폴더를 생성하고 다음을 통해 로컬로 설치합니다. npm 초기화 -y



npm init -y>

2 단계: 프로젝트 폴더를 생성한 후, 다음 명령어를 사용하여 해당 폴더로 이동하세요.

cd *project folder name*>

프로젝트 구조:

NodeProjs

프로젝트 구조



예시 1: 아래 예에서는 fs.writeFile() 메서드 Node.js에서:

자바스크립트


jframe



// Node.js program to demonstrate the> // fs.writeFile() method> // Import the filesystem module> const fs = require(>'fs'>);> let data = 'This is a file containing a collection of books.';> fs.writeFile('books.txt', data, (err) =>{> >if> (err)> >console.log(err);> >else> {> >console.log('File written successfully ');> >console.log('The written has the following contents:');> >console.log(fs.readFileSync('books.txt', 'utf8'));> >}> });>

>

>

산출:

File written successfully The written has the following contents: This is a file containing a collection of books.>

예시 2: 아래 예는 fs.writeFile() 메서드 Node.js에서:

자바스크립트




// Node.js program to demonstrate the> // fs.writeFile() method> // Import the filesystem module> const fs = require(>'fs'>);> let data = 'This is a file containing a collection of movies.';> fs.writeFile('movies.txt', data,> >{> >encoding: 'utf8',> >flag: 'w',> >mode: 0o666> >},> >(err) =>{> >if> (err)> >console.log(err);> >else> {> >console.log('File written successfully ');> >console.log('The written has the following contents:');> >console.log(fs.readFileSync('movies.txt', 'utf8'));> >}> });>

>

>

산출:

File written successfully The written has the following contents: This is a file containing a collection of movies.>