• Node.js Video Tutorials

Node.js - 檔案系統



Node.js API 是一種伺服器端程式設計技術。因此,Node.js 應用程式可能需要與伺服器的物理檔案系統互動。Node.js API 包含 fs 模組,使開發人員能夠對磁碟檔案執行讀/寫操作。Node.js 中的 fs 模組提供同步和非同步方法來處理檔案。

要使用檔案系統函式,您需要使用以下語法匯入 fs 模組:

var fs = require("fs")

同步與非同步

fs 模組中的每個方法都有同步和非同步版本。非同步方法將最後一個引數作為完成函式回撥,回撥函式的第一個引數作為錯誤。

例如,在檔案中寫入資料的同步方法是:

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

另一方面,它的非同步版本具有以下語法:

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

與同步方法相比,非同步方法是非阻塞的。

對於本章中的示例程式碼,我們將使用一個名為 input.txt 的文字檔案,其內容如下:

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

寫入檔案

以下程式演示瞭如何使用同步和非同步方法在檔案中寫入資料。

const fs = require('fs');
var text = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
`;

console.log("Writing synchronously");
fs.writeFileSync("input.txt", text);

console.log("Writing asynchronously");
fs.writeFile('input.txt', text, function (err) { 

   if (err)
      console.log(err);
   else
      console.log('Write operation complete.');
});

輸出

Writing synchronously
Writing asynchronously
Write operation complete.

讀取檔案

fs 模組中的 ReadFile() 方法非同步讀取檔案。它具有以下語法:

fs.readFile(fileName [,options], callback)

另一方面,ReadFileSync() 方法是其同步版本,具有以下語法:

fs.readFileSync(fileName [,options])

示例

以下程式同步和非同步地讀取 input.txt 檔案。

const fs = require('fs');

console.log("Reading synchronously");
data = fs.readFileSync("input.txt");
console.log(data.toString());

console.log("Reading asynchronously");
fs.readFile('input.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});
console.log('Read operation complete.');

輸出

Reading synchronously
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Reading asynchronously
Read operation complete.
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

開啟檔案

readFile() 和 writeFile() 方法隱式地開啟和關閉要讀取/寫入的檔案。相反,您可以顯式開啟檔案,設定檔案開啟模式以指示是用於讀取還是寫入,然後關閉檔案。

open() 方法具有以下簽名:

fs.open(path, flags[, mode], callback)

引數

  • path − 包含路徑的檔名字串。

  • flags − 標誌指示要開啟的檔案的行為。所有可能的值如下所示。

  • mode − 它設定檔案模式(許可權和粘滯位),但僅當建立檔案時才設定。預設為 0666,可讀和可寫。

  • callback − 這是回撥函式,它接收兩個引數 (err, fd)。

flag 引數的值為:

序號 標誌 & 描述
1

r

開啟檔案以進行讀取。如果檔案不存在,則會發生異常。

2

r+

開啟檔案以進行讀寫。如果檔案不存在,則會發生異常。

3

rs

以同步模式開啟檔案以進行讀取。

4

rs+

開啟檔案以進行讀寫,要求作業系統以同步方式開啟它。有關謹慎使用此方法,請參閱“rs”的說明。

5

w

開啟檔案以進行寫入。如果檔案不存在,則建立檔案;如果檔案存在,則截斷檔案。

6

wx

類似於“w”,但如果路徑存在則失敗。

7

w+

開啟檔案以進行讀寫。如果檔案不存在,則建立檔案;如果檔案存在,則截斷檔案。

8

wx+

類似於“w+”,但如果路徑存在則失敗。

9

a

開啟檔案以進行追加。如果檔案不存在,則建立檔案。

10

ax

類似於“a”,但如果路徑存在則失敗。

11

a+

開啟檔案以進行讀取和追加。如果檔案不存在,則建立檔案。

12

ax+

類似於“a+”,但如果路徑存在則失敗。

讓我們開啟一個名為“input.txt”的檔案,以便向其中寫入資料。

const fd = fs.open('input.txt', 'w', (err, fd) => {
   if (err) {
      console.log(err);
      return;
   }
});

open() 方法返回對檔案的引用,稱為檔案描述符。檔案描述符是一個唯一的整數,用作執行寫入和讀取操作的方法的引數。

fs 模組中的 write() 方法將資料儲存到 open() 方法返回的檔案描述符引用的檔案中。

write(fd, string[, position[, encoding]], callback)

引數

  • fd − 檔案描述符

  • string − 要寫入的資料

  • position − 從哪裡開始寫入 預設值:null

  • encoding − 字元編碼字串 預設值:'utf8'

  • callback − 要呼叫的回撥函式。

以下程式碼片段將給定的文字寫入我們上面開啟的檔案中。

var data = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
`;

if (err) {
   console.log(err);
   return;
}

始終建議關閉開啟的檔案,尤其是在以可寫模式開啟時。

// Close the file
fs.close(fd, (err) => {
   if (err) {
      console.log(err);
      return;
   }
});

讓我們將所有這些程式碼片段組合成一個程式,以可寫模式開啟檔案,向其中放入一些資料,然後關閉它。

示例

const fs = require('fs');

// Open a file for writing
const fd = fs.open('input.txt', 'w', (err, fd) => {
   if (err) {
      console.log(err);
      return;
   }

   // Write some data to the file
   var data = `Tutorials Point is giving self learning content
   to teach the world in simple and easy way!!!!!
   `;

   fs.write(fd, data, (err) => {
      if (err) {
         console.log(err);
         return;
      }

      // Close the file
      fs.close(fd, (err) => {
         if (err) {
            console.log(err);
            return;
         }

         console.log('The file was written successfully!');
      });
   });
});

執行後,上述程式會在當前目錄中建立 input.txt。

要讀迴文件,必須以讀取模式開啟它。fs 模組中的 read() 方法使用檔案描述符並在緩衝區物件中檢索其中的資料。

read(fd, buffer[, options], callback)

引數

  • fd − 檔案描述符

  • buffer − 資料將寫入到的緩衝區。

  • options − 偏移量、長度和位置

  • callback − 要呼叫的函式。

要讀回 input.txt 中的資料,請按如下方式使用 read() 方法:

示例

var fs = require('fs');

fs.open('test.txt', 'r', function (err, fd) {
    
   if (err) {
      return console.error(err);
   }
    
   var buffr = Buffer.alloc(1024);
    
   fs.read(fd, buffr, function (err) {
       
      if (err) throw err;
         else
      console.log(buffr.toString());
   });
        
   // Close the opened file.
   fs.close(fd, function (err) {
      if (err) throw err;
   });
});

執行上述程式。input.txt 的內容將被檢索並顯示在控制檯上。

Promise API

在 Node.js 應用程式中,如果需要非同步執行許多不同的活動,則可能會有大量的巢狀回撥。但是,程式碼隨後可能會變得雜亂無章,通常稱為回撥地獄。為了克服這個問題,JavaScript 引入了 Promise 的概念。

Promise 本質上是對執行非同步任務的回撥的改進。它表示將完成或拒絕的活動。如果 Promise 已完成,則將其解析;否則,將其拒絕。與典型的回撥不同,Promise 可以連結。

在 Node.js 10 版之後的版本中,fs 模組包含實現 Promise 概念的檔案管理方法。(回撥和同步方法也存在)。

新的非同步函式使用 async/await 語法。該函式以 async 關鍵字為字首,並且始終返回一個 Promise。await 關鍵字使 JavaScript 等待該 Promise 完成並返回其結果。

fs 模組中 writeFile() 方法的 Promise API 版本如下:

fsPromises.writeFile(file, data[, options])

引數

  • file − 檔名或 FileHandle

  • data − 字串或緩衝區。該方法返回一個 Promise 物件。它非同步地將資料寫入檔案,如果檔案已存在則替換該檔案。data 可以是字串或緩衝區。

以下程式使用 Promise 化的 writeFile() 方法。

示例

const fs = require("fs");
var data = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
`;
async function write_file() {
   await fs.promises.writeFile("input.txt", data);
   console.log("Data written successfully");
}

write_file();

另一方面,Promise API 中的 readFile() 方法具有以下語法:

fsPromises.readFile(path[, options])#

引數

  • path − 檔名或 FileHandle

  • options 包括 encoding、flag、signal

該方法返回 − 一個 Promise。它非同步地讀取檔案的全部內容。

示例

const fs = require("fs");

async function read_file() {
   const secret = await fs.promises.readFile("input.txt");
   console.log(secret.toString());
}

read_file();

要檢索檔案 (input.txt) 的內容,請儲存上述程式碼並從命令列執行。

獲取檔案資訊

語法

以下是獲取有關檔案資訊的方法的語法:

fs.stat(path, callback)

引數

以下是使用的引數說明:

  • path − 包含路徑的檔名字串。

  • callback − 這是回撥函式,它接收兩個引數 (err, stats),其中stats 是 fs.Stats 型別的物件,如下面的示例中所示。

除了下面示例中列印的重要屬性外,fs.Stats 類中還提供了一些有用的方法來檢查檔案型別。這些方法在下面的表中給出。

序號 方法 & 描述
1

stats.isFile()

如果檔案型別是簡單檔案,則返回 true。

2

stats.isDirectory()

如果檔案型別是目錄,則返回 true。

3

stats.isBlockDevice()

如果檔案型別是塊裝置,則返回 true。

4

stats.isCharacterDevice()

如果檔案型別是字元裝置,則返回 true。

5

stats.isSymbolicLink()

如果檔案型別是符號連結,則返回 true。

6

stats.isFIFO()

如果檔案型別是 FIFO,則返回 true。

7

stats.isSocket()

如果檔案型別是套接字,則返回 true。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");

console.log("Going to get file info!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
      return console.error(err);
   }
   console.log(stats);
   console.log("Got file info successfully!");
   
   // Check file type
   console.log("isFile ? " + stats.isFile());
   console.log("isDirectory ? " + stats.isDirectory());    
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to get file info!
{ 
   dev: 1792,
   mode: 33188,
   nlink: 1,
   uid: 48,
   gid: 48,
   rdev: 0,
   blksize: 4096,
   ino: 4318127,
   size: 97,
   blocks: 8,
   atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),
   mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),
   ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT) 
}
Got file info successfully!
isFile ? true
isDirectory ? false

關閉檔案

語法

以下是關閉開啟檔案的語法:

fs.close(fd, callback)

引數

以下是使用的引數說明:

  • fd − 這是 fs.open() 方法返回的檔案描述符。

  • callback − 這是回撥函式,除了可能的異常之外,沒有其他引數傳遞給完成回撥。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to read the file");
   
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
      if (err) {
         console.log(err);
      }

      // Print only read bytes to avoid junk.
      if(bytes > 0) {
         console.log(buf.slice(0, bytes).toString());
      }

      // Close the opened file.
      fs.close(fd, function(err) {
         if (err) {
            console.log(err);
         } 
         console.log("File closed successfully.");
      });
   });
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to open an existing file
File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

File closed successfully.

截斷檔案

語法

以下是截斷開啟檔案的方法的語法:

fs.ftruncate(fd, len, callback)

引數

以下是使用的引數說明:

  • fd − 這是 fs.open() 返回的檔案描述符。

  • len − 這是檔案在截斷後的長度。

  • callback − 這是回撥函式,除了可能的異常之外,沒有其他引數傳遞給完成回撥。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to truncate the file after 10 bytes");
   
   // Truncate the opened file.
   fs.ftruncate(fd, 10, function(err) {
      if (err) {
         console.log(err);
      } 
      console.log("File truncated successfully.");
      console.log("Going to read the same file"); 
      
      fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
         if (err) {
            console.log(err);
         }

         // Print only read bytes to avoid junk.
         if(bytes > 0) {
            console.log(buf.slice(0, bytes).toString());
         }

         // Close the opened file.
         fs.close(fd, function(err) {
            if (err) {
               console.log(err);
            } 
            console.log("File closed successfully.");
         });
      });
   });
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to open an existing file
File opened successfully!
Going to truncate the file after 10 bytes
File truncated successfully.
Going to read the same file
Tutorials 
File closed successfully.

刪除檔案

語法

以下是刪除檔案的方法的語法:

fs.unlink(path, callback)

引數

以下是使用的引數說明:

  • path − 包含路徑的檔名。

  • callback − 這是回撥函式,除了可能的異常之外,沒有其他引數傳遞給完成回撥。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");

console.log("Going to delete an existing file");
fs.unlink('input.txt', function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("File deleted successfully!");
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to delete an existing file
File deleted successfully!

建立目錄

語法

以下是建立目錄的方法的語法:

fs.mkdir(path[, mode], callback)

引數

以下是使用的引數說明:

  • path − 這是包含路徑的目錄名稱。

  • mode − 這是要設定的目錄許可權。預設為 0777。

  • callback − 這是回撥函式,除了可能的異常之外,沒有其他引數傳遞給完成回撥。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");

console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("Directory created successfully!");
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to create directory /tmp/test
Directory created successfully!

讀取目錄

語法

以下是讀取目錄的方法語法:

fs.readdir(path, callback)

引數

以下是使用的引數說明:

  • path − 這是包含路徑的目錄名稱。

  • callback − 這是一個回撥函式,它接收兩個引數 (err, files),其中 files 是一個數組,包含目錄中檔案的名稱,不包括 '.' 和 '..'。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");

console.log("Going to read directory /tmp");
fs.readdir("/tmp/",function(err, files) {
   if (err) {
      return console.error(err);
   }
   files.forEach( function (file) {
      console.log( file );
   });
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test
test.txt

刪除目錄

語法

以下是刪除目錄的方法語法:

fs.rmdir(path, callback)

引數

以下是使用的引數說明:

  • path − 這是包含路徑的目錄名稱。

  • callback − 這是回撥函式,除了可能的異常之外,沒有其他引數傳遞給完成回撥。

示例

讓我們建立一個名為main.js的 js 檔案,其中包含以下程式碼:

var fs = require("fs");

console.log("Going to delete directory /tmp/test");
fs.rmdir("/tmp/test",function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("Going to read directory /tmp");
   
   fs.readdir("/tmp/",function(err, files) {
      if (err) {
         return console.error(err);
      }
      files.forEach( function (file) {
         console.log( file );
      });
   });
});

現在執行 main.js 以檢視結果:

$ node main.js

驗證輸出。

Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test.txt

方法參考

廣告