เราสามารถอ่านไฟล์ข้อความและส่งคืนเนื้อหาเป็น Array โดยใช้ 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', '' ]
ตัวอย่าง (การใช้ async 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