Node.js สามารถเขียน อ่าน แก้ไขไฟล์ได้ผ่าน Module ที่ชื่อว่า fs (File System) มาลองดูตัวอย่างการจัดการไฟล์ด้วย Node.js แต่ละวีธี
Create File (สร้างไฟล์) & Update Files (แก้ไขไฟล์)
สร้างไฟล์ หรือ อัพเดทไฟล์โดยเขียนต่อด้านท้ายด้วยคำสั่ง fs.appendFile
var fs = require('fs');
fs.appendFile('myfile1.txt', 'Create or Update by fs.appendFile', function (err) {
if (err) throw err;
console.log('Saved!');
});
สร้างไฟล์ หรือ อัพเดทไฟล์โดยเขียนทับด้วยคำสั่ง fs.writeFile
var fs = require('fs');
fs.writeFile('myfile1.txt', 'Create or Update by fs.writeFile', function (err) {
if (err) throw err;
console.log('Saved!');
});
Delete Files (ลบไฟล์)
ลบไฟล์ด้วยคำสั่ง fs.unlink
var fs = require('fs');
fs.unlink('myfile3.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
จากคำสั่งด้านบนลบไฟล์ myfile3.txt
Rename Files (แก้ไขชื่อไฟล์)
แก้ไขชื่อไฟล์ด้วย fs.rename
var fs = require('fs');
fs.rename('myfile1.txt', 'myfile3.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
จากคำสั่งด้านบนจะทำการแก้ไฟล์ชื่อ myfile1.txt เป็น myfile3.txt
Read Files (อ่านไฟล์)
อ่านข้อมูลภายในไฟล์ด้วย fs.readFile
var fs = require("fs");
fs.readFile("input.txt", (err, data) => {
if (err) return console.error(err);
console.log(data.toString());
});