fs.writeFile()方法用于将指定的数据异步写入文件。默认情况下, 文件将被替换(如果存在)。 " options"参数可用于修改方法的功能。
语法如下:
fs.writeFile( file, data, options, callback )
参数:此方法接受上述和以下所述的四个参数:
- 文件:它是一个字符串, Buffer, URL或文件描述整数, 表示必须在其中写入文件的路径。使用文件描述符将使其行为类似于fs.write()方法。
- 数据:它是将写入文件的字符串, Buffer, TypedArray或DataView。
- 选项:它是一个字符串或对象, 可用于指定将影响输出的可选参数。它具有三个可选参数:
- 编码:它是一个字符串值, 用于指定文件的编码。默认值为" utf8"。
- 模式:它是一个整数值, 指定文件模式。默认值为0o666。
- 旗:它是一个字符串值, 用于指定在写入文件时使用的标志。默认值为" w"。
- 打回来:执行该方法时将调用该函数。
- 呃:如果操作失败, 将抛出此错误。
以下示例说明了fs.writeFile()方法在Node.js中:
范例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