1.fs.rename(oldPath, newPath, callback)
如果舊文件路徑(oldPath)和新文件路徑(newPath)在同一個文件夾下 如 ‘./a/b’和’./a/c’ 則是修改文件名或目錄名
fs.rename('./a/b','./a/c',function(error){
if(error){console.log("發生錯誤");}
else{
console.log('修改成功')
}
})
如果舊文件路徑(oldPath)和新文件路徑(newPath)不在同一個文件夾下 如 ‘./a/c’ 和 './b/c’則是移動文件
fs.rename('./a/c','./b/c',function(error){
if(error){console.log("發生錯誤");}
else{
console.log('移動成功')
}
})
2. fs.truncate(path[, len], callback) 將文件變爲指定大小
// 如果文件大小>len(長度) 則會進行截取 將多出來的全部刪除
// 如果文件大小<len(長度) 則會補充一堆看不懂的東西
fs.truncate(path,24,function(error){
if(error){}
else{
console.log("成功")
}
})
3.fs.watch(filename[, options][, listener]) 監聽文件或目錄變化
// filename: 監聽的文件名
// options:{} 對象
// persistent:若文件被監聽 程序是否一直執行下去
// recursive:是否監聽子目錄
// listener: 函數 接收兩個參數
// eventType:文件的變化類型 如 change改變
// filename 發生變動的文件名
fs.watch(path,{persistent:true,recursive:true},function(eventType,filename){
console.log(eventType);
console.log(filename);
})
4. fs.watchFile(filename[, options], listener) 監聽文件變化
// filename: 監聽的文件名
// options: {} 對象
// persistent <boolean> 默認值: true
// listener:函數 接收兩個參數
// current : 改變後文件的stat對象
// previous: 改變前文件的stat對象
fs.watchFile(path,{persistent:true},function(current,previous){
console.log(current);
console.log(previous);
})
5. fs.unlink(path,callback) 刪除文件
fs.unlink(path,function(error){
if(error){
console.log(error)
}
else{
console.log("刪除成功")
}
})
6. pipe配合Strem實現文件拷貝
let fs=require('fs');
6.1創建ReadStream和WriteStream
let source=fs.createReadStream(sourceFilePath); // 源文件
let target=fs.createWriteStream(targetFilePath); // 目標文件
6.2 使用pipe 將source中的數據拷貝到target中
第二個參數爲一個對象 end屬性爲true 則文件讀取完畢 會將兩個stream都關閉 false則不會
source.pipe(target,{end:true})