fs.writeFile()方法用于将指定的数据异步写入文件。默认情况下,文件将被替换(如果存在)。 “ options”参数可用于修改方法的函数。
用法:
fs.writeFile( file, data, options, callback )
参数:此方法接受上述和以下所述的四个参数:
- file:它是一个字符串,Buffer,URL或文件描述整数,表示必须在其中写入文件的路径。使用文件描述符将使其行为类似于fs.write()方法。
 - data:它是将写入文件的字符串,Buffer,TypedArray或DataView。
 - options:它是一个字符串或对象,可用于指定将影响输出的可选参数。它具有三个可选参数:
- encoding:它是一个字符串值,用于指定文件的编码。默认值为“ utf8”。
 - mode:它是一个整数值,指定文件模式。默认值为0o666。
 - flag:它是一个字符串值,用于指定写入文件时使用的标志。默认值为“ w”。
 
 - callback:执行该方法时将调用该函数。
- err:如果操作失败,将引发此错误。
 
 
以下示例说明了Node.js中的fs.writeFile()方法:
范例1:
// Node.js program to demonstrate the 
// fs.writeFile() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
let data = "This is a file containing a collection of books."; 
  
fs.writeFile("books.txt", data, (err) => { 
  if (err) 
    console.log(err); 
  else { 
    console.log("File written successfully\n"); 
    console.log("The written has the following contents:"); 
    console.log(fs.readFileSync("books.txt", "utf8")); 
  } 
});输出:
File written successfully The written has the following contents: This is a file containing a collection of books.
范例2:
// Node.js program to demonstrate the 
// fs.writeFile() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
let data = "This is a file containing a collection of movies."; 
  
fs.writeFile("movies.txt", data, 
  { 
    encoding:"utf8", 
    flag:"w", 
    mode:0o666 
  }, 
  (err) => { 
    if (err) 
      console.log(err); 
    else { 
      console.log("File written successfully\n"); 
      console.log("The written has the following contents:"); 
      console.log(fs.readFileSync("movies.txt", "utf8")); 
    } 
});输出:
File written successfully The written has the following contents: This is a file containing a collection of movies.
参考: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
相关用法
- Node.js GM drawCircle()用法及代码示例
 - Node.js GM drawBezier()用法及代码示例
 - Node.js GM drawPolyline()用法及代码示例
 - Node.js GM drawArc()用法及代码示例
 - Node.js GM drawEllipse()用法及代码示例
 - Node.js GM monochrome()用法及代码示例
 - Node.js GM equalize()用法及代码示例
 - Node.js GM enhance()用法及代码示例
 - Node.js GM drawPolygon()用法及代码示例
 - Node.js GM whitePoint()用法及代码示例
 
注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | fs.writeFile() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
