1. 程式人生 > 其它 >fs模組的其他方法

fs模組的其他方法

var fs = require('fs')

fs.existsSync(path) 檢查一個檔案是否存在
var isExists = fs.existsSync('hello.txt')

fs.statSync(path)
fs.stat(path, callback) 獲取檔案的狀態
- 它會返回一個物件,這個物件中儲存了當前物件狀態的相關資訊
- 回撥函式的形參有兩個,一個err,一個stat,stat裡面有幾個方法
size: 檔案的大小
isFile(): 是否是一個檔案
isDirectory(): 是否是一個資料夾

fs.stat('hello.txt', function(err, stat, ){
console.log(stat.size) //檔案的大小
})

fs.unlinkSync(path)
fs.unlink(path, callback) 刪除檔案
fs.unlink('hello.txt')

fs.readdirSync(path[, options])
fs.readdirSync(path[, options], callback) 讀取一個目錄的目錄結構
- files是一個字串陣列,每一個元素就是一個資料夾或檔案的名字

fs.readdir('.', function(err, files){ //'.' 代表當前目錄
if(!err){
console.log(files)
}
})

fs.truncateSync(path, len)
fs.truncateSync(path, len, callback) 截斷檔案,將檔案修改為指定大小位元組,注意:一個漢字佔3個位元組
fs.truncateSync('hello,txt', 3)

fs.mkdirSync(path[, mode])
fs.mkdir(path[, mode], callback) 建立一個目錄/資料夾
fs.mkdir('helloDir')

fs.rmdirSync(path[, mode])
fs.rmdir(path[, mode], callback) 刪除一個目錄/資料夾
fs.rmdir('helloDir')

fs.renameSync(oldPath, newPath)
fs.rename(oldPath, newPath, callback) 對資料夾進行重新命名(相當於剪下)
- 引數:
oldPath: 舊的路徑
newPath: 新的路徑
callback: 回撥函式

fs.rename('hello.txt', '你好.txt', function(err){
if(!err){
console.log('修改成功')
}
})

fs.watchFile(filename[, options], listener) 監視檔案的修改(內部是每隔一段時間就檢查一下是否發生變化)
- 引數:
filename: 要監視的檔案的名字
options: 配置選項
interval: 檢查間隔
listener: 回撥函式,當檔案發生變化時,回撥函式會執行
在回撥函式中會有兩個引數:
curr: 當前檔案的狀態
prev: 修改前檔案的狀態
這兩個物件都是stats物件(參考fs.stat)

fs.watchFile('hello.txt', {interval : 1000}, function(curr, prev){
console.log('修改前檔案大小:' + prev.size)
console.log('修改後(當前)檔案大小:' + curr.size)
})