您現在的位置是:首頁 > 手機遊戲首頁手機遊戲
「NodeJS」 檔案操作模組API使用
- 2022-03-29
操作模組是什麼
檔案操作相關API
引入檔案系統模組fs
const fs = require(‘fs’)
fs。readFile(path[, options], callback) 讀取檔案
path | | 檔案路路徑
callback 回撥函式errdata | 讀取的數
fs。readFile(‘。/hello。txt’,‘utf8’,(err,data) => {if(err) throw err;console。log(data);})
s。writeFile(file, data[, options], callback) 寫入檔案
file | | | 檔名或檔案描述符。
data | | | 寫入的資料
options |encoding | 寫入字串串的編碼格式 預設值: ‘utf8’ 。mode 檔案模式(許可權) 預設值: 0o666 。flag 參閱⽀支援的檔案系統標誌。預設值: ‘w’ 。
callback 回撥函式
err
fs。writeFile(‘。/hello。txt’,‘this is a test’,err => {if(err) throw err;console。log(‘寫⼊入成功’);})
fs。appendFile(path, data[, options], callback) 追加資料到檔案
path | | | 檔名或檔案描述符。
data | 追加的資料
options |·encoding | 寫入字串串的編碼格式 預設值: ‘utf8’ 。mode 檔案模式(許可權) 預設值: 0o666 。flag 參閱支援的檔案系統標誌。預設值: ‘a’
callback 回撥函式err
const buf = Buffer。from(‘hello world!’)fs。appendFile(‘。/hello。txt’,buf,(err) => {if(err) throw err;console。log(‘追加成功’);})
fs。stat(path[, options], callback) 獲取⽂檔案資訊,判斷檔案狀態(是檔案還是資料夾)
path | |
optionsbigint 返回的 fs。Stats 物件中的數值是否應為 bigint 型。預設值: false
callbackerrstats
fs。stat(‘。/hello。txtt’,(err,stats) => {if(err){console。log(‘檔案不不存在’);return;}console。log(stats);console。log(stats。isFile());console。log(stats。isDirectory());})
fs。rename(oldPath, newPath, callback) 重新命名檔案
oldPath | | 舊檔案路路徑名字
newPath | | 新檔案路路徑名字
callback 回撥函式err
fs。rename(‘。/hello。txt’,‘。/test。txt’,err => {if(err) throw err;console。log(‘重新命名成功’);})
s。unlink(path, callback) 刪除⽂檔案
path | |
callbackerr
fs。unlink(‘。/test。txt’,err => {if(err) throw err;console。log(‘刪除成功’);})
資料夾操作相關API
fs。mkdir(path[, options], callback) 建立⽂資料夾path | |options |recursive 是否遞迴建立 預設值: false 。mode 檔案模式(許可權)Windows 上不不支援。預設值: 0o777 。callbackerr
const fs =require(‘fs’);// fs。mkdir(‘。/a’,err => {// if(err) throw err;// console。log(‘建立資料夾成功’);// })fs。mkdir(‘。/b/c’,{recursive:true},err => {if(err) throw err;console。log(‘建立資料夾成功’);})
fs。readdir (path[, options], callback) 讀取資料夾
path | |
options |encoding 預設值: ‘utf8’ 。withFileTypes 預設值: false
callbackerrfiles
fs。readdir(‘。/’,{encoding:‘buffer’, //設定buffer,files返回檔名為buffer物件withFileTypes:true //單上檔案型別},(err,files) => {if(err) throw err;console。log(files)})
fs。rmdir(path[, options], callback) 刪除⽂資料夾
path | |
optionsmaxRetries 重試次數。出現這類錯誤 EBUSY 、 EMFILE 、 ENFILE 、 ENOTEMPTY 或
者EPERM ,每⼀一個重試會根據設定的重試間隔重試操作。如果 recursive不不為true則忽略略。 預設值: 0。retryDelay 重試的間隔,如果 recursive 不不為true則忽略略。 預設值: 100 。recursive 如果為 true ,則執⾏行行遞迴的⽬目錄刪除。在遞迴模式中,如果 path 不不存在則不不報告錯誤,並且在失敗時重試操作。預設值: false 。
fs。rmdir(‘。/b’,{recursive:true},err => {if(err) throw err;console。log(‘刪除⽂資料夾成功’);})
監聽檔案變化 chokidar
安裝chokidar
npm install chokidar ——save-dev- Chokidar。watch(path,[options])chokidar。watch(‘。/’,{ignored:‘。/node_modules’})。on(‘all’,(event,path) => {console。log(event,path)})