Node.js fs.writeFile() 方法
fs.writeFile() 方法用于将指定的数据异步写入文件。默认情况下,如果文件存在,将被替换。 'options' 参数可用于修改方法的功能。
句法:
fs.writeFile( file, data, options, callback )
参数:此方法接受上面提到的四个参数,如下所述:
- 文件:它是一个字符串、缓冲区、URL 或文件描述整数,表示必须写入的文件的路径。使用文件描述符将使其行为类似于 fs.write() 方法。
- 数据:它将被写入文件的字符串、缓冲区、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