fs.writeFileSync() 메서드는 동기 메서드입니다. 지정한 파일이 존재하지 않으면 새 파일을 생성합니다. 또한 'readline-sync' 모듈은 런타임 시 사용자 입력을 활성화하는 데 사용됩니다.
Node.js의 'fs' 모듈은 파일 I/O 작업을 구현합니다. fs 모듈 메소드는 동기식일 수도 있고 비동기식일 수도 있습니다. 비동기 함수에는 비동기 함수의 완료를 나타내는 마지막 매개변수로 콜백 함수가 있습니다. Node.js 개발자는 비동기식 메서드가 실행 중에 프로그램을 차단하지 않는 반면, 후자는 프로그램을 차단하지 않기 때문에 동기식 메서드보다 비동기식 메서드를 선호합니다.
메인 스레드를 차단하는 것은 Node.js에서 잘못된 행위이므로 동기 함수는 디버깅용으로만 사용하거나 다른 옵션을 사용할 수 없는 경우에만 사용해야 합니다.
통사론:
fs.writeFileSync( file, data, options )>
매개변수: 이 메서드는 위에서 언급하고 아래에 설명된 세 가지 매개 변수를 허용합니다.
- file: 작성해야 하는 파일의 경로를 나타내는 문자열, 버퍼, URL 또는 파일 설명 정수입니다. 파일 설명자를 사용하면 fs.write() 메서드와 유사하게 동작합니다. data: 파일에 기록될 문자열, Buffer, TypedArray 또는 DataView입니다. 옵션: 출력에 영향을 주는 선택적 매개변수를 지정하는 데 사용할 수 있는 문자열 또는 개체입니다. 여기에는 세 가지 선택적 매개변수가 있습니다.
- 인코딩: 파일의 인코딩을 지정하는 문자열입니다. 기본값은 'utf8'입니다. mode: 파일 모드를 지정하는 정수입니다. 기본값은 0o666입니다. flag: 파일에 쓰는 동안 사용되는 플래그를 지정하는 문자열입니다. 기본값은 'w'입니다.
아래 예는 fs.writeFileSync() 메서드 Node.js에서.
예시 1:
자바스크립트
// Node.js program to demonstrate the> // fs.writeFileSync() method> > // Import the filesystem module> const fs = require(>'fs'>);> > let data =>'This is a file containing a collection'> >+>' of programming languages.
'> >+>'1. C
2. C++
3. Python'>;> > fs.writeFileSync(>'programming.txt'>, data);> console.log(>'File written successfully
'>);> console.log(>'The written has the following contents:'>);> console.log(fs.readFileSync(>'programming.txt'>,>'utf8'>));> |
자식 푸시 명령
>
>
산출:
File written successfully The written has the following contents: This is a file containing a collection of programming languages. 1. C 2. C++ 3. Python>
예시 2:
자바스크립트
js 세트
// Node.js program to demonstrate the> // fs.writeFileSync() method> > // Import the filesystem module> const fs = require(>'fs'>);> > // Writing to the file 5 times> // with the append file mode> for> (let i = 0; i <5; i++) {> >fs.writeFileSync(>'movies.txt'>,> >'Movie '> + i +>'
'>,> >{> >encoding:>'utf8'>,> >flag:>'a+'>,> >mode: 0o666> >});> }> > console.log(>'File written successfully 5 times
'>);> console.log(>'The written file has the following contents:'>);> console.log(fs.readFileSync(>'movies.txt'>,>'utf8'>));> |
>
>
C 언어의 문자열 배열
산출:
File written successfully 5 times The written file has the following contents: Movie 0 Movie 1 Movie 2 Movie 3 Movie 4>
예시 3: readline 모듈을 사용하여 파일 이름 및 파일 데이터에 대해 사용자로부터 런타임 입력 가져오기
자바스크립트
let readline = require(>'readline-sync'>);> let fs = require(>'fs'>);> > let path = readline.question(>'Enter file name/path: '>);> > console.log(>'Entered path : '> + path);> > let data = readline.question(>'Enter file data: '>);> > //synchronous functions may throw errors> //which can be handled using try-catch block> try> {> >fs.writeFileSync(path, data, { flag:>'a+'> });>//'a+' is append mode> >console.log(>'File written successfully'>);> }>catch> (err) {> >console.error(err);> }> console.log(>'-----------------------------------------------'>);> try> {> >const data = fs.readFileSync(path, { encoding:>'utf8'> });> >console.log(>'File content is as follows:'>);> >// Display the file data> >console.log(data);> }>catch> (err) {> >console.log(err);> }> |
>
>
산출

예시 4: 버퍼를 사용하는 readline 모듈을 사용하여 파일 데이터에 대해 사용자로부터 런타임 입력을 가져옵니다.
자바스크립트
let fs = require(>'fs'>);> let readline = require(>'readline-sync'>);> let path = readline.question(>'Enter file name/path: '>);> > console.log(>'Entered path : '> + path);> > // 1024 specifies the buffer size. We can limit> // the data size by this approach> let buf =>new> Buffer.alloc(1024);> buf = readline.question(>'Enter data:'>);> > > try> {> >fs.writeFileSync(path, buf, { flag:>'a+'> });> >console.log(>'File written successfully'>);> }>catch> (err) {> >console.error(err);> }> console.log(>'-----------------------------------------------'>);> try> {> >const data = fs.readFileSync(path, { encoding:>'utf8'> });> >console.log(>'File content is as follows:'>);> >// Display the file data> >console.log(data);> }>catch> (err) {> >console.log(err);> }> |
쉐타 티와리
>
>
산출

참조: https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options