nodejs檔案相關操作

2021-10-12 05:21:33 字數 3174 閱讀 7543

nodejs中文文件

1.讀檔案
1.非同步讀取檔案全部內容fs.readfile(path[, options], callback)

let data= fs.readfile(video.id,function(err,data) console.log(data); })

2.同步讀取檔案全部內容

2.讀取目錄內容
1.非同步fs.readdir(path[, options], callback)

let flist = fs.readdirsync(that.fileloc,function(err,files) console.log(files); })

2.同步fs.readdirsync(path[, options])

2.寫檔案
1.非同步fs.writefile(file, data[, options], callback)

當 file 是檔名時,則非同步地寫入資料到檔案(如果檔案已存在,則覆蓋檔案)。 data 可以是字串或 buffer。

//sspath:檔案目錄,例如:e:\hb\demo\demohtml.txt  

//buf:檔案流,

//quan:許可權

let quan =

fs.writefile

(sspath, buf, quan,

function

(err)

)

2.同步fs.writefilesync(file, data[, options])

fs.writefile(sspath, buf, quan)

3.判斷檔案是否存在
1.非同步fs.exists()已棄用2.同步fs.existssync(path)

if (fs.existssync('檔案'))

4.檔案大小
1.非同步fs.statsync(path[, options])

let stats = fs.stat(video.src,function(err,stats) console.log(stats)})

2.同步

fs.stat(path[, options], callback)

let stats = fs.statsync(video.src)

console.log(stats)

//檔案大小

[官方建議]:不建議在呼叫 fs.open()、 fs.readfile() 或 fs.writefile() 之前使用 fs.stat() 檢查檔案的存在性。 而是應該直接地開啟、讀取或寫入檔案,如果檔案不可用,則處理引發的錯誤。

若要只檢查檔案是否存在,但沒有更多的操作,則建議使用 fs.access()。

5.刪除檔案
1.非同步fs.unlink(path, callback)

fs.unlink('檔案.txt', (err) => );

2.同步

fs.unlinksync(path)

fs.unlinksync('檔案.txt')

6.建立目錄
1.非同步fs.mkdir(path[, options], callback)

// 建立 "/目錄1/目錄2/目錄3",不管 "/目錄1 和 /目錄1/目錄2" 是否存在。

fs.mkdir('/目錄1/目錄2/目錄3', , (err) => );

當 path 是已存在的目錄時,呼叫 fs.mkdir() 僅在 recursive 為 false 時才會導致錯誤。

2.同步

fs.mkdirsync(path[, options])

fs.mkdirsync(_path);

7.刪除目錄
1.非同步fs.rmdir(path[, options], callback)

2.同步

fs.rmdirsync(path[, options])

fs.rmdirsync(that.spath)

Nodejs檔案操作相關流失操作(二)

基於檔案流操作 基於檔案流操作檔案 readfile和writefiel是一次性將檔案讀取到記憶體這樣對記憶體很不友好,而基於檔案流操作會根據需要將內容一段段的讀取到記憶體 大檔案操作 流式操作 fs.createreadstream path fs.createwritestream path c...

nodejs 操作檔案

1.首先引入模組fs varfs require fs 2.方法 2.1非同步刪除檔案 fs.unlink home hello function err console.log 成功刪除檔案 2.2同步 刪除檔案 fs.unlinksync home hello console.log 成功刪除檔...

nodejs裡mysql的相關操作

該 採用mysql.js作為本文的資料庫連線庫,由於使用express故先介紹express下的資料庫配置,關於mysql的安裝這裡不作介紹,可以參考 mac安裝mysql的兩種方法。當然這個過程並非是一番豐順的,出現過很多錯誤,如 總之,一般都可以在stackoverflow上找到答案。mysql...