Để khai báo ta dùng:
const fs = require('fs');
Môt số hàm ta có thể dùng: Hàm readFile: đọc nội dung file. Hàm này cần callback để có thể lấy nội dung file.
fs.readFile('path-to-file', function (err, data) {
});
Hàm readFileSync: cũng có tác dụng đọc file. Tuy nhiên nó là hàm đồng bộ (sync), không cần callback để xử lý dữ liệu.
let content = fs.readFileSync('path-to-file', 'utf-8');
Hàm appendFile, có tác dụng append 1 nội dung vào file.
fs.appendFile(filePath, content, (err) => {
});
Hàm rename, đổi tên file
fs.rename('path', 'new-path', function (err){});
Hàm unlink: xóa file
fs.unlink('path', function (err) {});
Hàm unlinkSync: xóa file đồng bộ
fs.unlink('path');
Hàm createReadStream: tạo ra 1 stream read file khi có sự thay đổi ở file. Sau đó ta có thể bind vào response của server bằng cách dùng .pipe(res)
. res là 1 instance của ServerResponse.
fs.createReadStream('./index.html').pipe(res);