當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs.readFileSync()用法及代碼示例

fs.readFileSync()方法是fs模塊的內置應用程序編程接口,用於讀取文件並返回其內容。

在fs.readFile()方法中,我們可以以非阻塞異步方式讀取文件,但在fs.readFileSync()方法中,我們可以以同步方式讀取文件,即,我們告訴node.js阻塞其他並行進程並執行當前的文件讀取過程。即,當調用fs.readFileSync()方法時,原始節點程序停止執行,並且節點等待fs.readFileSync()函數執行,獲得該方法的結果後,其餘節點程序將被執行。

用法:



fs.readFileSync( path, options )

參數:

  • path:它采用文本文件的相對路徑。路徑可以是URL類型。該文件也可以是文件描述符。如果兩個文件都在同一個文件夾中,隻需在文件名中加上引號即可。
  • options:它是一個可選參數,包含編碼和標誌,編碼包含數據規範。默認值為null,它返回原始緩衝區,並且該標誌包含文件中操作的指示。默認值為“ r”。

返回值:此方法返回文件的內容。

範例1:

  • input.txt文件內容:
    This is some text data which is stored in input.txt file.
  • index.js文件:
    // Node.js program to demonstrate the   
    // fs.readFileSync() method  
      
    // Include fs module 
    const fs = require('fs'); 
       
    // Calling the readFileSync() method 
    // to read 'input.txt' file 
    const data = fs.readFileSync('./input.txt', 
                {encoding:'utf8', flag:'r'}); 
      
    // Display the file data 
    console.log(data);
  • 輸出:
    This is some text data which is stored in input.txt file.
    

現在,問題是該fs.readFileSync()方法與fs.readFile()方法有何不同。我們可以找到一個何時使用fs.readFileSync()方法和fs.readFile()方法的示例。

假設有兩個輸入文件input1.txt和input2.txt,並且兩個文件都保存在同一文件夾中。

範例2:

  • input1.txt文件的內容:
    (1) This is some text data which is stored in input1.txt file.
  • input2.txt文件內容:
    (2) This is some text data which is stored in input2.txt file.
  • index.js文件:
    // Node.js program to demonstrate the   
    // fs.readFileSync() method  
      
    // Include fs module 
    const fs = require('fs'); 
       
    // Callling the fs.readFile() method 
    // for reading file 'input1.txt' 
    fs.readFile('./input1.txt',  
            {encoding:'utf8', flag:'r'}, 
            function(err, data) { 
        if(err) 
            console.log(err); 
        else
            console.log(data); 
    }); 
       
    // Calling the fs.readFileSync() method  
    // for reading file 'input2.txt' 
    const data = fs.readFileSync('./input2.txt', 
                  {encoding:'utf8', flag:'r'}); 
      
    // Display data 
    console.log(data);
  • 輸出:
    (2) This is some text data which is stored in input2.txt file.
    (1) This is some text data which is stored in input1.txt file.
    

觀察:我們可以觀察到,當我們調用讀取“ input1.txt”的fs.readFile()方法之後,我們調用了讀取“ input2.txt”文件的fs.readFileSync()方法,但是看到輸出,我們發現首先讀取“ input2.txt”文件,然後讀取“ input1.txt”文件,這是因為編譯器編譯node.js文件時,它首先調用fs.readFile()方法,該方法讀取文件,但是並行執行後,它將繼續編譯其餘文件程序也是如此,之後它調用fs.readFileSync()方法讀取另一個文件,當調用readFileSync()方法時,編譯器將停止其他並行進程(此處是從readFile()方法中讀取“ input1.txt”文件)並繼續進行中的過程到此結束,無論正在進行的進程何時結束,編譯器都會恢複剩餘的進程,這就是為什麽我們觀察到首先打印“ input2.txt”的內容而不是“ input1.txt”的原因。因此,我們可以使用fs.readFileSync()方法執行諸如暫停其他並行進程並同步讀取文件之類的任務。

參考: https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options




相關用法


注:本文由純淨天空篩選整理自NigattennoGokui大神的英文原創作品 Node.js | fs.readFileSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。