fs-extra 中的 outputFile() 函数 - NodeJS
异步 outputFile() 函数简介
此方法类似于 'fs' 的写入文件方法。唯一的区别在于,如果父目录不存在,它将创建父目录。传递的参数始终应为文件路径,而不是缓冲区或文件描述符。
语法
outputFile(file, data[, options] [, callback])
参数
file – 字符串参数,包含文件的名称和位置。
data – 数据可以保存字符串数据、缓冲区流或要存储的 Unit8 字符串数组。
options – 'outputFile' 函数支持以下选项:
encoding – 默认值 'utf8'。
mode – 默认值 0o666
signal – 允许中止正在进行的输出文件函数
callback – 如果发生任何错误,此函数将提供回调。
示例
在继续之前,请检查是否已安装 fs-extra;如果未安装,请安装 fs-extra。
您可以使用以下命令检查是否已安装 fs-extra。
npm ls fs-extra
创建一个 asyncOutputFile.js 文件,并将以下代码片段复制粘贴到该文件中。
现在,运行以下命令以运行以下代码片段。
node asyncOutputFile.js
代码片段:
const fs = require('fs-extra')
const file = '/tmp/not/exist/file.txt'
// Writing file with a callback:
fs.outputFile(file, 'Welcome to Tutorials Point!', err => {
console.log(err) // => null
fs.readFile(file, 'utf8', (err, data) => {
if (err) return console.error(err)
console.log(data) // => Welcome to Tutorials Point!
})
})
// Writing file with Promises:
fs.outputFile(file, 'Welcome to Tutorials Point!')
.then(() => fs.readFile(file, 'utf8'))
.then(data => {
console.log(data) // => Welcome to Tutorials Point!
})
.catch(err => {
console.error(err)
})
// Writing file async/await:
async function asyncOutputFileExample (f) {
try {
await fs.outputFile(f, 'Welcome to Tutorials Point!')
const data = await fs.readFile(f, 'utf8')
console.log(data) // => Welcome to Tutorials Point!
} catch (err) {
console.error(err)
}
}
asyncOutputFileExample(file)输出
C:\Users\tutorialsPoint\> node asyncOutputFile.js null Welcome to Tutorials Point! Welcome to Tutorials Point! Welcome to Tutorials Point!
outputFileSync() 函数简介
此方法与 'fs' 中的 writeFileSync 方法相同。唯一的区别在于,如果父目录不存在,它将创建父目录。传递的参数始终应为文件路径,而不是缓冲区或文件描述符。
语法
outputFileSync(file, data[, options])
参数
file – 这是一个字符串参数,将保存文件的位置。
data – 数据可以保存字符串数据、缓冲区流或要存储的 Unit8 字符串数组。
options – 'outputFile' 函数支持以下选项:
encoding – 默认值 'utf8'。
mode – 默认值 0o666
flag – 文件操作的不同标志选项
示例
在继续之前,请检查是否已安装 fs-extra;如果未安装,请安装 fs-extra。
您可以使用以下命令检查是否已安装 fs-extra。
npm ls fs-extra
创建一个 outputFileSyncExample.js 文件,并将以下代码片段复制粘贴到该文件中。
现在,运行以下命令以运行以下代码片段。
node outputFileSyncExample.js
代码片段
const fs = require('fs-extra')
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.outputFileSync(file, 'Welcome to Tutorials Point!')
const data = fs.readFileSync(file, 'utf8')
console.log(data) // => Welcome to Tutorials Point!输出
C:\Users\tutorialsPoint\> node outputFileSyncExample.js Welcome to Tutorials Point!
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP