Giải thích chi tiết về module fs trong Node.js

Khám phá toàn bộ API của module fs (phi Promise) trong Node.js

Module fs trong Node.js hỗ trợ thao tác tập tin đồng bộ và bất đồng bộ. Dưới đây là phân tích chi tiết các phương thức không sử dụng Promise:

1. Thao tác đọc tập tin

const fs = require('fs');

// Đọc tập tin bất đồng bộ
fs.readFile('input.txt', 'utf8', (err, nộiDung) => {
  if (err) {
    console.error('Lỗi đọc tập tin:', err);
    return;
  }
  console.log('Nội dung:', nộiDung);
});

// Đọc tập tin đồng bộ
try {
  const nộiDung = fs.readFileSync('data.txt', 'utf8');
  console.log('Nội dung:', nộiDung);
} catch (err) {
  console.error('Lỗi đọc tập tin:', err);
}

// Sử dụng mô tả tập tin để đọc
fs.open('source.txt', 'r', (err, môTả) => {
  if (err) {
    console.error('Lỗi mở tập tin:', err);
    return;
  }
  
  const buffer = Buffer.alloc(200);
  fs.read(môTả, buffer, 0, 200, 0, (err, bytesRead, buffer) => {
    if (err) {
      console.error('Lỗi đọc dữ liệu:', err);
      fs.close(môTả, () => {});
      return;
    }
    console.log('Số byte đọc được:', bytesRead);
    console.log('Nội dung:', buffer.toString());
    
    fs.close(môTả, (err) => {
      if (err) console.error('Lỗi đóng tập tin:', err);
    });
  });
});

2. Thao tác ghi tập tin

// Ghi tập tin bất đồng bộ
fs.writeFile('kết_qua.txt', 'Xin chào thế giới', 'utf8', (err) => {
  if (err) {
    console.error('Lỗi ghi tập tin:', err);
    return;
  }
  console.log('Ghi tập tin thành công');
});

// Ghi tập tin đồng bộ
try {
  fs.writeFileSync('output.txt', 'Xin chào thế giới', 'utf8');
  console.log('Ghi tập tin thành công');
} catch (err) {
  console.error('Lỗi ghi tập tin:', err);
}

// Thêm nội dung
fs.appendFile('log.txt', 'Đăng ký mới\n', 'utf8', (err) => {
  if (err) {
    console.error('Lỗi thêm nội dung:', err);
    return;
  }
  console.log('Thêm nội dung thành công');
});

// Ghi qua mô tả tập tin
fs.open('target.txt', 'w', (err, môTả) => {
  if (err) {
    console.error('Lỗi mở tập tin:', err);
    return;
  }
  
  fs.write(môTả, 'Xin chào', 0, 'utf8', (err, written, string) => {
    if (err) {
      console.error('Lỗi ghi dữ liệu:', err);
      fs.close(môTả, () => {});
      return;
    }
    console.log('Số byte ghi:', written);
    
    fs.close(môTả, (err) => {
      if (err) console.error('Lỗi đóng tập tin:', err);
    });
  });
});

3. Các thao tác tập tin

// Sao chép tập tin
fs.copyFile('nguồn.txt', 'đích.txt', (err) => {
  if (err) {
    console.error('Lỗi sao chép:', err);
    return;
  }
  console.log('Sao chép thành công');
});

// Đổi tên tập tin
fs.rename('cũ.txt', 'mới.txt', (err) => {
  if (err) {
    console.error('Lỗi đổi tên:', err);
    return;
  }
  console.log('Đổi tên thành công');
});

// Xóa tập tin
fs.unlink('tập_tin.txt', (err) => {
  if (err) {
    console.error('Lỗi xóa tập tin:', err);
    return;
  }
  console.log('Xóa tập tin thành công');
});

// Tạo liên kết cứng
fs.link('nguồn.txt', 'liên_kết.txt', (err) => {
  if (err) {
    console.error('Lỗi tạo liên kết cứng:', err);
    return;
  }
  console.log('Tạo liên kết cứng thành công');
});

// Tạo liên kết tượng trưng
fs.symlink('mục_tiêu.txt', 'liên_kết_tượng_trưng.txt', (err) => {
  if (err) {
    console.error('Lỗi tạo liên kết tượng trưng:', err);
    return;
  }
  console.log('Tạo liên kết tượng trưng thành công');
});

// Đọc liên kết tượng trưng
fs.readlink('liên_kết_tượng_trưng.txt', (err, đườngDẫn) => {
  if (err) {
    console.error('Lỗi đọc liên kết:', err);
    return;
  }
  console.log('Mục tiêu liên kết:', đườngDẫn);
});

// Lấy thông tin tập tin
fs.stat('tập_tin.txt', (err, thôngTin) => {
  if (err) {
    console.error('Lỗi lấy thông tin:', err);
    return;
  }
  console.log('Là tập tin:', thôngTin.isFile());
  console.log('Kích thước:', thôngTin.size);
  console.log('Tạo lúc:', thôngTin.birthtime);
  console.log('Cập nhật lúc:', thôngTin.mtime);
});

// Thay đổi quyền truy cập
fs.chmod('tập_tin.txt', 0o666, (err) => {
  if (err) {
    console.error('Lỗi thay đổi quyền:', err);
    return;
  }
  console.log('Thay đổi quyền thành công');
});

// Thay đổi chủ sở hữu
fs.chown('tập_tin.txt', 1000, 1000, (err) => {
  if (err) {
    console.error('Lỗi thay đổi chủ sở hữu:', err);
    return;
  }
  console.log('Thay đổi chủ sở hữu thành công');
});

4. Thao tác thư mục

// Tạo thư mục
fs.mkdir('thư_mục_mới', { recursive: true }, (err) => {
  if (err) {
    console.error('Lỗi tạo thư mục:', err);
    return;
  }
  console.log('Tạo thư mục thành công');
});

// Đọc thư mục
fs.readdir('thư_mục', (err, danhSách) => {
  if (err) {
    console.error('Lỗi đọc thư mục:', err);
    return;
  }
  console.log('Nội dung thư mục:', danhSách);
});

// Xóa thư mục
fs.rmdir('thư_mục_trống', (err) => {
  if (err) {
    console.error('Lỗi xóa thư mục:', err);
    return;
  }
  console.log('Xóa thư mục thành công');
});

// Xóa thư mục đệ quy
fs.rm('thư_mục', { recursive: true, force: true }, (err) => {
  if (err) {
    console.error('Lỗi xóa thư mục đệ quy:', err);
    return;
  }
  console.log('Xóa thư mục đệ quy thành công');
});

// Lấy thông tin thư mục
fs.stat('thư_mục', (err, thôngTin) => {
  if (err) {
    console.error('Lỗi lấy thông tin thư mục:', err);
    return;
  }
  console.log('Là thư mục:', thôngTin.isDirectory());
});

// Thay đổi quyền truy cập thư mục
fs.chmod('thư_mục', 0o755, (err) => {
  if (err) {
    console.error('Lỗi thay đổi quyền thư mục:', err);
    return;
  }
  console.log('Thay đổi quyền thư mục thành công');
});

5. Giám sát tập tin

// Giám sát thay đổi tập tin
const theoDõi = fs.watch('tập_tin.txt', (loạiSựKiện, tênTậpTin) => {
  console.log(`Sự kiện: ${loạiSựKiện}, Tập tin: ${tênTậpTin}`);
});

// Dừng giám sát
theoDõi.close();

// Giám sát thư mục
const theoDõiThuMuc = fs.watch('thư_mục', { recursive: true }, (loạiSựKiện, tênTậpTin) => {
  console.log(`Sự kiện thư mục: ${loạiSựKiện}, Tập tin: ${tênTậpTin}`);
});

// Dừng giám sát thư mục
theoDõiThuMuc.close();

6. Thao tác luồng dữ liệu

// Tạo luồng đọc
const luồngĐọc = fs.createReadStream('input.txt', {
  encoding: 'utf8',
  highWaterMark: 128 * 1024 // Kích thước đệm 128KB
});

// Tạo luồng ghi
const luồngGhi = fs.createWriteStream('output.txt', {
  encoding: 'utf8',
  flags: 'a'
});

// Xử lý sự kiện luồng
luồngĐọc.on('data', (khối) => {
  console.log('Nhận khối dữ liệu:', khối);
});

luồngĐọc.on('end', () => {
  console.log('Đọc xong dữ liệu');
});

luồngĐọc.on('error', (lỗi) => {
  console.error('Lỗi đọc:', lỗi);
});

// Kết nối luồng
luồngĐọc.pipe(luồngGhi);

// Đóng luồng
luồngĐọc.destroy();
luồngGhi.end();

7. Tập tin tạm thời

// Tạo thư mục tạm thời
fs.mkdtemp('tiền_đề-', (err, thưMục) => {
  if (err) {
    console.error('Lỗi tạo thư mục tạm thời:', err);
    return;
  }
  console.log('Thư mục tạm thời:', thưMục);
  
  // Tạo tập tin trong thư mục tạm
  const tậpTin = path.join(thưMục, 'tạm.txt');
  fs.writeFile(tậpTin, 'Nội dung tạm thời', (err) => {
    if (err) {
      console.error('Lỗi tạo tập tin tạm:', err);
      return;
    }
    console.log('Tập tin tạm tại:', tậpTin);
  });
});

8. Thông tin hệ thống tập tin

// Lấy thông tin hệ thống tập tin
fs.statfs('/', (err, thôngTin) => {
  if (err) {
    console.error('Lỗi lấy thông tin hệ thống:', err);
    return;
  }
  console.log('Không gian tổng cộng:', thôngTin.blocks * thôngTin.bsize);
  console.log('Không gian trống:', thôngTin.bfree * thôngTin.bsize);
});

// Lấy mô tả tập tin
fs.open('tập_tin.txt', 'r', (err, môTả) => {
  if (err) {
    console.error('Lỗi mở tập tin:', err);
    return;
  }
  console.log('Mô tả tập tin:', môTả);
  fs.close(môTả, (err) => {
    if (err) console.error('Lỗi đóng tập tin:', err);
  });
});

9. Xử lý lỗi

// Kiểm tra sự tồn tại của tập tin
fs.access('tập_tin_không_tồn_tại.txt', fs.constants.F_OK, (err) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.log('Tập tin không tồn tại');
    } else if (err.code === 'EACCES') {
      console.log('Không có quyền truy cập');
    } else {
      console.error('Lỗi khác:', err);
    }
  } else {
    console.log('Tập tin tồn tại');
  }
});

10. Hằng số

// Các chế độ mở tập tin
const chếĐộ = {
  ĐỌC: fs.constants.O_RDONLY,
  GHI: fs.constants.O_WRONLY,
  ĐỌC_GHI: fs.constants.O_RDWR,
  GHI_KẾT_HỢP: fs.constants.O_APPEND,
  TẠO: fs.constants.O_CREAT,
  RIÊNG: fs.constants.O_EXCL,
  XOÁ: fs.constants.O_TRUNC
};

// Các loại tập tin
const loại = {
  TẬP_TIN: fs.constants.S_IFREG,
  THƯ_MỤC: fs.constants.S_IFDIR,
  LIÊN_KẾT_TƯỢNG_TRƯNG: fs.constants.S_IFLNK,
  CỔNG: fs.constants.S_IFSOCK,
  THIẾT_BỊ_KÝ_TỰ: fs.constants.S_IFCHR,
  THIẾT_BỊ_KHỐI: fs.constants.S_IFBLK,
  FIFO: fs.constants.S_IFIFO
};

Các phương thức trên là những API chính của module fs trong Node.js (phi Promise). So với phiên bản dùng Promise, các phương thức này sử dụng hàm callback thay vì trả về Promise.

Thẻ: nodejs filesystem fs-module asynchronous synchronous

Đăng vào ngày 18 tháng 5 lúc 02:08