Node.js filehandle.writeFile() 类中的方法:FileHandle
filehandle.writeFile()方法用于在 Node.js 的文件系统模块中定义。文件系统模块基本上是与用户计算机的硬盘进行交互的。 fs.writeFile() 方法将数据异步写入文件,如果文件已存在则替换该文件。
句法:
filehandle.writeFile(data, options)
参数:此方法接受上面提到的两个参数,如下所述:
- data:它是一个 String、Buffer 或 Uint8Array 实例。它将写入文件的数据。
- options:它是一个可选参数,以某种方式影响输出,因此我们是否将其提供给函数调用。
- encoding:它是一个指定编码技术的字符串,默认值为'utf8'。
示例 1:此示例说明如何对已存在的文件执行写入操作。
// Node.js program to demonstrate the
// filehandle.writeFile() Method
// Importing File System and Utilities module
const fs = require('fs')
// The readFileSync() method reads the
// contents of the file and returns the
// buffer form of the data
const oldBuff = fs.readFileSync('./tesTfile.txt')
const oldContent = oldBuff.toString()
console.log(`\nOld content of the file :\n${oldContent}`)
const writeToFile = async (path, data) => {
let filehandle = null
try {
filehandle = await fs.promises.open(path, mode = 'w')
// Write to file
await filehandle.writeFile(data)
} finally {
if (filehandle) {
// Close the file if it is opened.
await filehandle.close();
}
}
// New content after write operation
const newBuff = fs.readFileSync('./tesTfile.txt')
const newContent = newBuff.toString()
console.log(`\nNew content of the file :\n${newContent}`)
}
writeToFile('./testFile.txt', "Hey, I am newly added!")
.catch(err => {
console.log(`Error Occurs, Error code ->
${err.code}, Error NO -> ${err.errno}`)
})
输出:
示例 2:此示例说明如何将完成的操作写入之前不存在但在运行时创建的文件。
// Node.js program to demonstrate the
// filehandle.writeFile() Method
// Importing File System and Utilities module
const fs = require('fs')
const writeToFile = async (path, data) => {
let filehandle = null
try {
filehandle = await fs
.promises.open(path, mode = 'w')
// Write to file
await filehandle.writeFile(data)
} finally {
if (filehandle) {
// Close the file if it is opened.
await filehandle.close();
}
}
// The readFileSync() method reads
// the contents of the file and
// returns the buffer form of the data
const buff = fs.readFileSync(path)
const content = buff.toString()
console.log(`\nContents of the file :\n${content}`)
}
var query = "Hey there, I am newly added "
+ "content of newly added file!";
writeToFile('./testFile.txt', query)
.catch(err => {
console.log(`Error Occurs, Error code ->
${err.code}, Error NO -> ${err.errno}`)
})
运行程序前的目录结构:
运行程序后的目录结构:
输出: