fs 讀和寫

fs 讀寫文件

fs.opensync(path[]) sync是同步 async是異步
fs是nodejs核心模塊,需要引入才能使用

同步寫入文件:分為3步

打開文件

  • fs.openSync(path[, flags, mode]) []代表可選值
    • path 文件路徑
    • flags 可選值,一定有默認(rèn)值 'r' 要對文件進(jìn)行的操作 w是寫入
    • mode 可選值,一定有默認(rèn)值 0o666 設(shè)置文件的操作權(quán)限
      • 0o666 可讀可寫
      • 0o111 文件可執(zhí)行
      • 0o222 文件可寫入
      • 0o444 文件可讀取
        fs的返回值:表示文件描述符的整數(shù)。

寫入文件

  • fs.writeSync(fd, string[, position[, encoding]])
    • fd 文件描述符的整數(shù)
    • string 寫入的內(nèi)容
    • position 從哪個(gè)位置開始 0
    • encoding 編碼方式 utf-8
    • 返回值:寫入的字節(jié)數(shù)

關(guān)閉文件

  • fs.closeSync(fd)
// 引入fs
const fs = require('fs');

// 打開文件
const fd = fs.openSync('./a.txt', 'a');
console.log(fd);

// 寫入文件
const byte = fs.writeSync(fd, '111今天天氣真晴朗~');
console.log(byte);

// 關(guān)閉文件
fs.closeSync(fd);

異步寫入文件

打開文件
  • fs.open(path[, flags[, mode]], callback)
    • callback
      • err 錯(cuò)誤對象:如果方法出錯(cuò)了,值就是錯(cuò)誤對象,如果方法沒有出錯(cuò),就是null
      • 錯(cuò)誤優(yōu)先機(jī)制:要求開發(fā)者寫異步代碼優(yōu)先處理錯(cuò)誤
寫入文件
  • fs.write(fd, string[, position[, encoding]], callback)
關(guān)閉文件
  • fs.close(fd, callback)
使用async +promise 避免回調(diào)地獄
const fs = require('fs');

fs.open('./b.txt', 'w', (err, fd) => {
  // 判斷方法有無錯(cuò)誤
  if (err) {
    // 出錯(cuò)了~
    console.log('open方法出錯(cuò)了: ', err);
  } else {
    // 沒有出錯(cuò)
    fs.write(fd, '鋤禾日當(dāng)午', (err) => {
      if (err) {
        console.log('write方法出錯(cuò)了:', err);
      } else {

      }
      // 不管寫入成功或者失敗,都要關(guān)閉文件
      fs.close(fd, (err) => {
        if (err) {
          console.log('write方法出錯(cuò)了:', err);
        } else {

        }
      })
    })
  }
});
//這個(gè)是避免回調(diào)嵌套
(async () => {
  // 打開文件
  const fd = await new Promise((resolve, reject) => {
    // 執(zhí)行異步操作
    fs.open('c.txt', 'w', (err, fd) => {
      if (!err) {
        // 將promise對象改為成功狀態(tài)
        resolve(fd);
      } else {
        // 將promise對象改為失敗狀態(tài)
        reject(err);
      }
    })
  });
  // 寫入文件
  await new Promise((resolve, reject) => {
    fs.write(fd, '汗滴禾下土', (err) => {
      if (!err) {
        resolve();
      } else {
        // 打印錯(cuò)誤信息
        console.error(err);
        resolve(err);
      }
    })
  });
  // 關(guān)閉文件
  await new Promise((resolve, reject) => {
    fs.close(fd, (err) => {
      if (!err) resolve();
      else reject(err);
    })
  })

})();

簡單寫法

fs.writeFile(file, data[, options], callback) data寫入的數(shù)據(jù)

fs.writeFile('d.txt', '窗前明月光', (err) => {
  if (!err) {
    console.log('文件寫入成功~');
  } else {
    console.log(err);
  }
});

簡單讀取文件

  • fs.readFile(path,callpack)
    • callpack
      • err
      • data 讀取的文件內(nèi)容 是一個(gè)buffer數(shù)據(jù),想要看具體內(nèi)容,需要tostring
fs.readFile('./package.json', (err, data) => {
  if (!err) {
    console.log(data.toString());
  } else {
    console.log(err);
  }
});

stat 文件的數(shù)據(jù)
const {readFile, stat, watchFile} = require("fs");
stat("文件路徑",(err,stats)=>{
stats就是文件的信息
放入etag(stats) 就會(huì)生成一個(gè)獨(dú)有的id
})
監(jiān)聽 當(dāng)文件css改變時(shí),就會(huì)觸發(fā)
watchFile(css, (curr, prev) => {
curr就是現(xiàn)在的文件
etagName = etag(curr); //curr 中 有stats
lastModified = new Date().toGMTString()
});

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容