1. 程式人生 > 其它 >1.基礎模組/4、fs - 檔案系統

1.基礎模組/4、fs - 檔案系統

技術標籤:node.jssystemd

fs - 檔案系統

1 file system-檔案讀寫

  1. 讀取檔案(fs.readFile)
  2. 寫入檔案(fs.writeFile)
  3. 流程:引入fs模組 -> 呼叫方法 -> 異常捕獲

1.1、寫入檔案方法(非同步、同步)

1.1.1、fs.writeFile(file, data[, options], callback)

  • file<string> | <Buffer> | <URL> | <integer> 檔名或檔案描述符。
  • data <string> | <Buffer> | <TypeArray> | <DataView>
  • options <Object>| <string>
    • encoding <string> | <null> 預設值: 'utf8'
    • mode <integer> 預設值: 0o666
    • flag 參見檔案系統 flag 的支援預設值: 'w'
  • callback<Function>
    • err <Error>

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

fs.writeFile('檔案.txt', 'Node.js 中文網', 'utf8', callback)
;

1.1.2、fs.writeFileSync(file, data[, options])

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

fs.writeFile('檔案.txt', 'Node.js 中文網', 'utf8');

2.1、讀取檔案方法(非同步、同步)

2.1.1、fs.readFile(path[, options], callback)

  • path <string> | <Buffer> | <URL> | <integer> 檔名或檔案描述符。

  • options <Object> | <string>

  • callback <Function>

    • err<Error>
    • data <string> | <Buffer>

非同步地讀取檔案的全部內容。

fs.readFile('檔名', (err, data) => {
  if (err) throw err;
  console.log(data);
});

2.1.2、fs.readFileSync(path[, options])

  • path <string> | <Buffer> | <URL> | <integer> 檔名或檔案描述符。

  • options <Object> | <string>`

  • 返回:<string> | <Buffer>

返回 path 的內容。

2 file system-目錄的建立和刪除

  1. 建立資料夾(fs.mkdir)
  2. 刪除資料夾(fs.rmdir)
  3. 刪除檔案(fs.unlink)
  4. 流程:引入fs模組 -> 呼叫方法 -> 異常捕獲

2.1建立目錄

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

在這裡插入圖片描述

非同步地建立目錄。

// 建立 `/目錄1/目錄2/目錄3`,不管 `/目錄1` 和 `/目錄1/目錄2` 是否存在。
fs.mkdir('/目錄1/目錄2/目錄3', (err) => {
  if (err) throw err;
});

2.1.2同步建立目錄fs.mkdirSync(path[, options])

在這裡插入圖片描述
同步地建立目錄。

2.2 刪除目錄

2.2.1 非同步刪除fs.rmdir(path[, options], callback)

在這裡插入圖片描述
在這裡插入圖片描述

2.2.2 同步刪除fs.rmdirSync(path[, options])

在這裡插入圖片描述

2.3刪除檔案

fs.unlink(path, callback)

  • path <string> | <Buffer> | <URL>
  • callback <Function>
    • err<Error>

非同步地刪除檔案或符號連結。

const fs = require('fs')

fs.unlink('writeMe.txt'function(err){
    if (err) throw err
    console.log('檔案刪除成功!')
})

fs.unlink() 對空或非空的目錄均不起作用。 若要刪除目錄,則使用 fs.rmdir()

3 file system - 檔案重新命名

fs.rename(oldPath, newPath, callback)在這裡插入圖片描述

非同步地把 oldPath 檔案重新命名為 newPath 提供的路徑名。 如果 newPath 已存在,則覆蓋它。

fs.rename('舊檔案.txt', '新檔案.txt', (err) => {
  if (err) throw err;
  console.log('重新命名完成');
});