Node.js 文件写入参数
在 Node.js 中使用 fs.writeFile()
方法写入文件时,可以传递以下参数:
1. 文件路径
指定要写入的文件的路径。可以是绝对路径或相对于当前工作目录的相对路径。
2. 数据
要写入文件的数据。可以是字符串、Buffer 或包含数据块的数组。
3. 选项(可选)
一个包含可选配置的 JavaScript 对象。可以包括以下属性:
- encoding:数据编码,默认为 \'utf8\'。
- mode:文件权限模式,默认为 0o666。
- flag:打开文件时的标记,默认为 \'w\'(覆盖写入)。
示例:
<code class="javascript">const fs = require(\'fs\'); fs.writeFile(\'myFile.txt\', \'Hello world!\', (err) => { if (err) throw err; console.log(\'File written successfully.\'); }); // 使用选项 fs.writeFile(\'myFile2.txt\', \'Hello again!\', { encoding: \'ascii\' }, (err) => { if (err) throw err; console.log(\'File written successfully with ASCII encoding.\'); });