Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีอ่านและเขียนไฟล์ด้วย JavaScript

คุณไม่สามารถอ่านหรือเขียนไฟล์ใน JS ฝั่งไคลเอนต์ (เบราว์เซอร์) ได้ สามารถทำได้ฝั่งเซิร์ฟเวอร์โดยใช้โมดูล fs ใน Node.js โมดูลนี้มีฟังก์ชัน sync และ async สำหรับอ่าน/เขียนไฟล์ในระบบไฟล์

มาสร้างไฟล์ 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 module ใน Node.js ได้ที่ Tutorialspoint Node.js File System