Thuta Learning
ရှာဖွေရန်
IntermediateWeb Developmentbeginner

File System (fs)

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

fs module က File System နဲ့အလုပ်လုပ်ဖို့ Node.js built-in module ပါ။ File ဖတ်ခြင်း၊ file ရေးခြင်း၊ folder စစ်ခြင်း၊ log file သိမ်းခြင်း၊ JSON data ဖတ်ခြင်းလို backend အလုပ်တွေမှာမကြာခဏသုံးပါတယ်။

javascript
const fs = require('fs');

const note = 'Node.js can write files!';

// Write a file
fs.writeFile('note.txt', note, 'utf8', (writeErr) => {
  if (writeErr) {
    console.error('Write error:', writeErr.message);
    return;
  }

  // Read the file after writing
  fs.readFile('note.txt', 'utf8', (readErr, data) => {
    if (readErr) {
      console.error('Read error:', readErr.message);
      return;
    }

    console.log('File content:', data);
  });
});

အရင်ဆုံး note.txt file တစ်ခုရေးပါတယ်။ Write ပြီးမှ callback ထဲမှာ fs.readFile() နဲ့ပြန်ဖတ်ပါတယ်။ Error ရှိရင် return နဲ့ function ကိုရပ်ပြီး error message ပြပါတယ်။

You should see
File content: Node.js can write files!

Info

File path မမှန်ရင် read/write error ဖြစ်နိုင်ပါတယ်။ Production app တွေမှာ error handling မပါဘဲ file operation မရေးသင့်ပါ။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • File ကိုဖတ်ပြီးမှ file ရေးထားတာမပြီးသေးရင် empty/old data ဖြစ်နိုင်ပါတယ်။ Async code တွေမှာ order ကို callback, promise, async/await နဲ့သေချာထိန်းပါ။

လေ့ကျင့်ခန်း

User upload log, server activity log, small JSON config file, generated report file စတာတွေကို fs module နဲ့စီမံနိုင်ပါတယ်။

You'll know it worked when:

File System (fs) | Thuta Learning