node.js를 사용하여 텍스트 파일을 읽고 그 내용을 배열로 반환할 수 있습니다. 이 배열 내용을 사용하여 행을 처리하거나 단지 읽기를 위해 사용할 수 있습니다. 파일 읽기를 처리하기 위해 'fs' 모듈을 사용할 수 있습니다. fs.readFile() 및 fs.readFileSync() 메서드는 파일 읽기에 사용됩니다. 이 방법을 사용하여 큰 텍스트 파일을 읽을 수도 있습니다.
예(readFileSync() 사용)
fileToArray.js라는 이름의 파일을 만들고 아래 코드 스니펫을 복사합니다. 파일을 생성한 후 다음 명령을 사용하여 아래 예와 같이 이 코드를 실행하십시오 -
node fileToArray.js
fileToArray.js
// Importing the fs module
let fs = require("fs")
// Intitializing the readFileLines with the file
const readFileLines = filename =>
fs.readFileSync(filename)
.toString('UTF8')
.split('\n');
// Calling the readFiles function with file name
let arr = readFileLines('tutorialsPoint.txt');
// Printing the response array
console.log(arr); 출력
C:\home\node>> node fileToArray.js [ 'Welcome to TutorialsPoint !', 'SIMPLY LEARNING', '' ]
예(비동기 readFile() 사용)
예를 하나 더 살펴보겠습니다.
// Importing the fs module
var fs = require("fs")
// Intitializing the readFileLines with filename
fs.readFile('tutorialsPoint.txt', function(err, data) {
if(err) throw err;
var array = data.toString().split("\n");
for(i in array) {
// Printing the response array
console.log(array[i]);
}
}); 출력
C:\home\node>> node fileToArray.js Welcome to TutorialsPoint ! SIMPLY LEARNING