最近有在做日志文件的分析,其中有一個需求:A服務(wù)器項(xiàng)目需要用Nodejs監(jiān)聽日志文件的變化,當(dāng)項(xiàng)目產(chǎn)生了新的日志信息,將新的部分通過socket傳輸?shù)紹服務(wù)器項(xiàng)目。socket暫時不做分析。
這個需求很簡單,通過分析我們開始擼碼吧。 在擼碼的過程中還能鞏固所學(xué)Nodejs的API,何樂而不為呢?
所用的API
fs.watchFile()
語法
fs.watchFile(filename[, options], listener)
參數(shù)解析
filename <string> | <Buffer> | <URL> ——文件名options <Object> persistent <boolean> 默認(rèn)值: true。——是否應(yīng)該繼續(xù)運(yùn)行 interval <integer> 默認(rèn)值: 5007。——輪詢目標(biāo)的頻率listener <Function> current <fs.Stats> ——當(dāng)前值 previous <fs.Stats> ——之前值
監(jiān)視 filename 的更改。 每當(dāng)訪問文件時都會調(diào)用 listener 回調(diào)。
listener 有兩個參數(shù),當(dāng)前的 stat 對象和之前的 stat 對象
這些 stat 對象是 fs.Stat 的實(shí)例。
要在修改文件(而不僅僅是訪問)時收到通知,則需要比較 curr.mtime 和 prev.mtime。
當(dāng) fs.watchFile 操作導(dǎo)致 ENOENT 錯誤時,它將調(diào)用一次監(jiān)聽器,并將所有字段置零(或?qū)⑷掌谠O(shè)為 Unix 紀(jì)元)。 如果文件是在那之后創(chuàng)建的,則監(jiān)聽器會被再次調(diào)用,且?guī)献钚碌?stat 對象。 這是 v0.10 之后的功能變化。
使用 fs.watch() 比 fs.watchFile 和 fs.unwatchFile 更高效。 應(yīng)盡可能使用 fs.watch 代替 fs.watchFile 和 fs.unwatchFile。
當(dāng) fs.watchFile() 正在監(jiān)視的文件消失并重新出現(xiàn)時,第二次回調(diào)事件(文件重新出現(xiàn))返回的 previousStat 會與第一次回調(diào)事件(文件消失)返回的 previousStat 相同。
這種情況發(fā)生在:
文件被刪除,然后又恢復(fù)。例子
fs.watchFile('message.text', (curr, prev) => { console.log(`當(dāng)前的最近修改時間是: ${curr.mtime}`); console.log(`之前的最近修改時間是: ${prev.mtime}`);});fs.open()
語法
fs.open(path[, flags[, mode]], callback)
參數(shù)解析
path <string> | <Buffer> | <URL> ——文件路徑flags <string> | <number> 默認(rèn)值: 'r'。——文件系統(tǒng)標(biāo)志mode <integer> 默認(rèn)值: 0o666(可讀寫)。——設(shè)置文件模式(權(quán)限和粘滯位),但僅限于創(chuàng)建文件的情況callback <Function> err <Error> ——錯誤 fd <integer>——文件系統(tǒng)流
fs.read()
語法
fs.read(fd, buffer, offset, length, position, callback)
參數(shù)解析
fd <integer> ——文件系統(tǒng)流buffer <Buffer> | <TypedArray> | <DataView>——數(shù)據(jù)將寫入的緩沖區(qū)offset <integer>—— buffer 中開始寫入的偏移量length <integer>——要讀取的字節(jié)數(shù)position <integer>——從文件中開始讀取的位置callback <Function> err <Error> bytesRead <integer> buffer <Buffer>
新聞熱點(diǎn)
疑難解答
圖片精選