ข้ามไปยังเนื้อหา

File System

Node มาพร้อม filesystem operations เดียวกันใน API สามแบบที่แตกต่างกัน:

รูปแบบImportใช้เมื่อไหร่
Callback (async)import fs from 'node:fs'code เก่า, Node streams
Synchronousimport fs from 'node:fs'CLI scripts, config ตอน startup
Promise (async)import fs from 'node:fs/promises'server code ทั้งหมดที่เขียนใหม่
import fs from 'node:fs';
fs.readFile('./hello.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
Node.js

Needs the Node.js runtime — open in StackBlitz to run.

writeFile สร้างไฟล์ถ้ายังไม่มี และ แทนที่ เนื้อหาถ้ามีอยู่แล้ว ใช้ appendFile เพื่อเพิ่มต่อจากไฟล์ที่มีอยู่

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

import { readFileSync } from 'node:fs';
// Acceptable at startup — process has not yet started accepting requests
const config = JSON.parse(readFileSync('./config.json', 'utf8'));

อย่าเรียก readFileSync ใน request handler, route callback หรือ function ใดที่ถูกเรียกหลังจาก server เริ่มทำงาน

ทำไมควรหลีกเลี่ยง fs.readFileSync ใน server request handler?
fs.writeFile ทำอะไรถ้าไฟล์ปลายทางมีอยู่แล้ว?
import ใดที่ให้ promise-based fs API?