File System
fs module สามรูปแบบ
หัวข้อที่มีชื่อว่า “fs module สามรูปแบบ”Node มาพร้อม filesystem operations เดียวกันใน API สามแบบที่แตกต่างกัน:
| รูปแบบ | Import | ใช้เมื่อไหร่ |
|---|---|---|
| Callback (async) | import fs from 'node:fs' | code เก่า, Node streams |
| Synchronous | import fs from 'node:fs' | CLI scripts, config ตอน startup |
| Promise (async) | import fs from 'node:fs/promises' | server code ทั้งหมดที่เขียนใหม่ |
การอ่านไฟล์
หัวข้อที่มีชื่อว่า “การอ่านไฟล์”แบบ Callback
หัวข้อที่มีชื่อว่า “แบบ Callback”import fs from 'node:fs';
fs.readFile('./hello.txt', 'utf8', function(err, data) { if (err) throw err; console.log(data);});แบบ Promise (แนะนำ)
หัวข้อที่มีชื่อว่า “แบบ Promise (แนะนำ)”Needs the Node.js runtime — open in StackBlitz to run.
การเขียนไฟล์
หัวข้อที่มีชื่อว่า “การเขียนไฟล์”writeFile สร้างไฟล์ถ้ายังไม่มี และ แทนที่ เนื้อหาถ้ามีอยู่แล้ว ใช้ appendFile เพื่อเพิ่มต่อจากไฟล์ที่มีอยู่
Needs the Node.js runtime — open in StackBlitz to run.
การตรวจสอบการมีอยู่และ stats
หัวข้อที่มีชื่อว่า “การตรวจสอบการมีอยู่และ stats”Needs the Node.js runtime — open in StackBlitz to run.
Synchronous reads — เฉพาะตอน startup
หัวข้อที่มีชื่อว่า “Synchronous reads — เฉพาะตอน startup”import { readFileSync } from 'node:fs';
// Acceptable at startup — process has not yet started accepting requestsconst config = JSON.parse(readFileSync('./config.json', 'utf8'));อย่าเรียก readFileSync ใน request handler, route callback หรือ function ใดที่ถูกเรียกหลังจาก server เริ่มทำงาน