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ò)誤
- callback
寫入文件
- 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
- callpack
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()
});