Node.js檔案系統


Node實現檔案I/O使用標準的POSIX函式的簡單包裝。Node檔案系統(FS)模組可以使用以下語法輸入:

var fs = require("fs")

同步和非同步

在fs模組的每一個方法都有同步和非同步形式。非同步方法需要最後一個引數為完成回撥函式和回撥函式的第一個引數是錯誤的。它優選使用非同步方法來代替同步方法,前者從來不阻止程式的執行,作為第二使用。

範例

建立一個名為input.txt的檔案有以下內容的文字

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

讓我們建立一個名為具有以下程式碼main.js一個js檔案。

var fs = require("fs");

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

// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

console.log("Program Ended");

現在執行main.js看到的結果:

$ node main.js

驗證輸出

Synchronous read: Yiibai Point is giving self learning content
to teach the world in simple and easy way!!!!!

Program Ended
Asynchronous read: Yiibai Point is giving self learning content
to teach the world in simple and easy way!!!!!

以下部分將提供有關主要檔案I/ O方法很好的例子。

開啟一個檔案

語法

以下是在非同步模式下開啟檔案的方法的語法:

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

引數

下面是使用的引數的說明:

  • path - 這是檔案名,包括路徑字串。

  • flags - 標誌告知要開啟的檔案的行為。所有可能的值已經提及以下。

  • mode - 這將設定檔案模式(許可和黏性位),但前提是在建立該檔案。它預設為0666,讀取和寫入。

  • callback - 這是回撥函式得到兩個引數(err, fd)。

Flags

標誌進行讀/寫操作是:

Flag 描述
r 開啟檔案進行讀取。如果該檔案不存在發生異常。
r+ 開啟檔案進行讀取和寫入。如果該檔案不存在發生異常。
rs 開啟檔案,用於讀取在同步方式。
rs+ 開啟檔案進行讀取和寫入,告訴OS同步地開啟它。對於'rs'有關使用此慎用見註解。
w 開啟檔案進行寫入。該檔案被建立(如果它不存在)或截斷(如果它存在)。
wx 類似'w',如果路徑存在則失敗。
w+ 開啟檔案進行讀取和寫入。該檔案被建立(如果它不存在)或截斷(如果它存在)。
wx+ 類似“w+”,但如果路徑存在則失敗。
a 開啟檔案進行追加。如果它不存在,則建立該檔案。
ax 類似“a”,但如果路徑存在則失敗。
a+ 開啟檔案進行讀取和附加。如果它不存在,則建立該檔案。
ax+ 類似'a+',但如果路徑存在則失敗。

範例

讓我們建立一個名為main.js一個js檔案具有下面的程式碼,用於開啟一個檔案input.txt的讀寫。

var fs = require("fs");

// Asynchronous - Opening File
console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }
  console.log("File opened successfully!");     
});

現在執行main.js看到的結果:

$ node main.js

驗證輸出

Going to open file!
File opened successfully!

獲取檔案資訊

語法

下面是獲取一個檔案有關的資訊的方法的語法:

fs.stat(path, callback)

語法

下面是使用的引數的說明:

  • path - 這是有檔案名,包括路徑字串。

  • callback - 這是回撥函式得到兩個引數(err, stats) ,其中統計資料是這是印在下面的例子中的fs.Stats型別的物件。

除了這些在下面的例子中列印的重要屬性, 還有可以用於檢查檔案型別的fs.Stats類可用的有用的方法。這些方法列於下表中。

方法 描述
stats.isFile() 返回true,如果檔案型別是一個簡單的檔案
stats.isDirectory() 返回true,如果檔案型別是目錄
stats.isBlockDevice() 返回true,如果檔案型別是塊裝置
stats.isCharacterDevice() 返回true,如果檔案型別是字元裝置
stats.isSymbolicLink() 返回true,如果檔案型別是符號連線
stats.isFIFO() 返回true,如果檔案型別是FIFO
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.writeFile(filename, data[, options], callback)

這種方法如果檔案已經存在將會覆蓋檔案。如果想寫入到現有的檔案,那麼你應該使用其他的方法。

引數

下面是使用的引數的說明:

  • path - 這是有檔案名,包括路徑字串

  • data - 這是字串或緩衝將被寫入到檔案中

  • options - 第三個引數是一個物件,它將於{編碼,模式,標誌}。預設編碼是UTF8,模式是八進位制值0666和標誌 'w'

  • callback - 這是回撥函式獲取一個引數err,並用於在發生任何寫入錯誤返回錯誤。

範例

讓我們建立一個名為main.js的js檔案具有下面的程式碼:

var fs = require("fs");

console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!',  function(err) {
   if (err) {
       return console.error(err);
   }
   console.log("Data written successfully!");
   console.log("Let's read newly written data");
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});

現在執行main.js看到的結果:

$ node main.js

驗證輸出

Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!

讀取檔案

語法

以下是從檔案讀取的方法之一的語法:

fs.read(fd, buffer, offset, length, position, callback)

此方法將使用檔案描述符來讀取檔案,如果你想直接使用檔案名,那麼應該使用其他可用的方法來讀取檔案。

引數

下面是使用的引數的說明:

  • fd - 這是通過檔案fs.open()方法返回的檔案描述符

  • buffer - 這是該資料將被寫入到緩衝器

  • offset - 這是偏移量在緩衝器開始寫入處

  • length - 這是一個整數,指定要讀取的位元組的數目

  • position - 這是一個整數,指定從檔案中開始讀取。如果位置為null,資料將從當前檔案位置讀取。

  • callback - 這是回撥函式獲取三個引數,(err, bytesRead, buffer).

範例

讓我們建立一個名為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);
      }
      console.log(bytes + " bytes read");
      
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

現在執行main.js看到的結果:

$ node main.js

驗證輸出

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

關閉檔案

語法

以下是關閉一個開啟的檔案的方法之一的語法:

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
Yiibai 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
Yiibai 
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),其中檔案的檔案名的目錄中的陣列排除 '.' 和  '..'.

範例

讓我們建立一個名為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