learn:fs.mjs 888 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { writeFile, appendFile, readFile } from 'node:fs/promises';
  2. /**
  3. *! writeFile 写
  4. */
  5. export async function writeFileAsync() {
  6. try {
  7. await writeFile('./log.txt', 'heheda');
  8. console.log('写入成功');
  9. } catch (error) {
  10. console.error('写入失败:', error);
  11. }
  12. }
  13. /**
  14. *! appendFile 向文件末尾追加内容
  15. */
  16. export async function appendFileAsync(data = '') {
  17. try {
  18. await appendFile('./log.append.txt', data);
  19. console.log('写入成功');
  20. } catch (error) {
  21. console.error('写入失败:', error);
  22. }
  23. }
  24. /**
  25. *! readFile 读取文件内容
  26. */
  27. export async function readFileAsync() {
  28. try {
  29. // 默认读取的内容 是 二进制数据的16进制编码 数据
  30. // let content = await readFile('./log.append.txt');
  31. let content = await readFile('./log.append.txt', 'utf8');
  32. console.log(content);
  33. } catch (error) {}
  34. }