当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。