fsPromises.writeFile()方法用于将指定的数据异步写入文件。默认情况下,该文件将被替换(如果存在)。 ‘options’参数可用于修改方法的函数。
承诺将成功解决,毫无争议。
用法:
fsPromises.writeFile( file, data, options )
参数:此方法接受上述和以下所述的三个参数:
- file:它是一个字符串,Buffer,URL或文件描述整数,表示必须在其中写入文件的路径。使用文件描述符将使其行为类似于fsPromises.write()方法。
 - data:它是将写入文件的字符串,Buffer,TypedArray或DataView。
 - options:它是一个字符串或对象,可用于指定将影响输出的可选参数。它具有三个可选参数:
- encoding:它是一个字符串值,用于指定文件的编码。默认值为“ utf8”。
 - mode:它是一个整数值,指定文件模式。默认值为0o666。
 - flag:它是一个字符串值,用于指定在写入文件时使用的标志。默认值为‘w’。
 
 
返回值:此方法返回一个Promise。
以下示例说明了Node.js中的fsPromises.writeFile()方法:
范例1:
// Node.js program to demonstrate the  
// fsPromises.writeFile() method  
  
// Import the filesystem module  
const fs = require('fs'); 
const fsPromises = require('fs').promises; 
let data = "This is a file containing"
        + " a collection of movies."; 
  
(async function main() { 
    try { 
        await fsPromises.writeFile( 
                "movies.txt", data) 
  
        console.log("File written successfully"); 
        console.log("The written file has"
            + " the following contents:"); 
  
        console.log("" +  
            fs.readFileSync("./movies.txt")); 
  
    } catch (err) { 
        console.error(err); 
    } 
})();输出:
File written successfully The written file has the following contents: This is a file containing a collection of movies.
范例2:
// Node.js program to demonstrate the  
// fsPromises.writeFile() method  
  
// Import the filesystem module  
const fs = require('fs'); 
const fsPromises = require('fs').promises; 
let data = "This is a file containing"
        + " a collection of books."; 
  
(async function main() { 
    try { 
  
        await fsPromises.writeFile( 
                "books.txt", data, { 
            encoding:"utf8", 
            flag:"w", 
            mode:0o666 
        }); 
  
        console.log("File written successfully\n"); 
        console.log("The written has the "
                + "following contents:"); 
  
        console.log("" +  
            fs.readFileSync("books.txt")); 
    } 
    catch (err) { 
        console.error(err); 
    } 
})();输出:
File written successfully The written has the following contents: This is a file containing a collection of books.
参考: https://nodejs.org/api/fs.html#fs_fspromises_writefile_file_data_options
相关用法
- Node.js console.timeLog()用法及代码示例
 - Node.js GM segment()用法及代码示例
 - Node.js GM blur()用法及代码示例
 - Node.js GM bordercolor()用法及代码示例
 - Node.js GM equalize()用法及代码示例
 - Node.js GM paint()用法及代码示例
 - Node.js GM enhance()用法及代码示例
 - Node.js GM roll()用法及代码示例
 - Node.js GM sepia()用法及代码示例
 - Node.js GM charcoal()用法及代码示例
 - Node.js GM resize()用法及代码示例
 - Node.js GM transparent()用法及代码示例
 - Node.js GM thumbnail()用法及代码示例
 - Node.js GM chop()用法及代码示例
 
注:本文由纯净天空筛选整理自nitin_sharma大神的英文原创作品 Node.js | fsPromises.writeFile() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
