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


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


fs.writeFileSync()方法用於將數據同步寫入文件。如果該文件已經存在,則替換該文件。 “ options”參數可用於修改方法的函數。

用法:

fs.writeFileSync( file, data, options )

參數:此方法接受上述和以下所述的三個參數:



  • file:它是一個字符串,Buffer,URL或文件描述整數,表示必須在其中寫入文件的路徑。使用文件描述符將使其行為類似於fs.write()方法。
  • data:它是將寫入文件的字符串,Buffer,TypedArray或DataView。
  • options:它是一個字符串或對象,可用於指定將影響輸出的可選參數。它具有三個可選參數:
    • encoding:它是一個字符串,它指定文件的編碼。默認值為“ utf8”。
    • mode:它是一個整數,指定文件模式。默認值為0o666。
    • flag:它是一個字符串,指定在寫入文件時使用的標誌。默認值為“ w”。

以下示例說明了Node.js中的fs.writeFileSync()方法:

範例1:

// Node.js program to demonstrate the 
// fs.writeFileSync() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
let data = "This is a file containing a collection"
           + " of programming languages.\n"
 + "1. C\n2. C++\n3. Python"; 
  
fs.writeFileSync("programming.txt", data); 
console.log("File written successfully\n"); 
console.log("The written has the following contents:"); 
console.log(fs.readFileSync("programming.txt", "utf8"));

輸出:

File written successfully

The written has the following contents:
This is a file containing a collection of programming languages.
1. C
2. C++
3. Python

範例2:

// Node.js program to demonstrate the 
// fs.writeFileSync() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
// Writing to the file 5 times 
// with the append file mode 
for (let i = 0; i < 5; i++) { 
  fs.writeFileSync("movies.txt", 
    "Movie " + i + "\n", 
    { 
      encoding:"utf8", 
      flag:"a+", 
      mode:0o666 
    }); 
} 
  
console.log("File written successfully 5 times\n"); 
console.log("The written file has the following contents:"); 
console.log(fs.readFileSync("movies.txt", "utf8"));

輸出:

File written successfully 5 times

The written file has the following contents:
Movie 0
Movie 1
Movie 2
Movie 3
Movie 4

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





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