คุณไม่สามารถอ่านหรือเขียนไฟล์ใน JS ทางฝั่งไคลเอ็นต์ (เบราว์เซอร์) สามารถทำได้บนฝั่งเซิร์ฟเวอร์โดยใช้โมดูล fs ใน Node.js มีฟังก์ชันซิงค์และอะซิงโครนัสเพื่ออ่านและเขียนไฟล์บนระบบไฟล์ ให้เราดูตัวอย่างของการอ่านและเขียนไฟล์โดยใช้โมดูล fs บน node.js
ให้เราสร้างไฟล์ js ชื่อ main.js โดยมีรหัสดังต่อไปนี้ -
var fs = require("fs");
console.log("Going to write into existing file");
// Open a new file with name input.txt and write Simply Easy Learning! to it.
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
// Read the newly written file and print all of its content on the console
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}); ตอนนี้เรียกใช้ main.js เพื่อดูผลลัพธ์ -
$ node main.js
ผลลัพธ์
Going to write into existing file Data written successfully! Let's read newly written data Asynchronous read: Simply Easy Learning!
คุณสามารถอ่านเพิ่มเติมเกี่ยวกับวิธีการทำงานของโมดูล fs ในโหนดและวิธีใช้งานได้ที่ https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm