fs 文件系统
- fs 文件系统提供了异步、同步两种方法来读取文件,如
readFile()/readFileSync
- 异步读取的最后一个参数为回调函数,回调函数的第一个参为 err 错误提示,第二个参为 data 数据
- 异步读取性能好,不阻塞
同步操作文件(进程阻塞)
fs.readFileSync(path)
同步读取文件
path
路径
- 无回调,直接回返回
data
const path = ''
const fs = require('fs')
const data = fs.readFileSync(path)
异步操作文件(非阻塞)
fs.readFile(path, callback(err, data))
异步读取文件
path
路径
callback(err, data)
, err
错误信息,data
读取的数据
fs.readFile(path, (err, data) => {
if (err) {
return console.error(err)
}
console.log(data.toString())
})
`
fs write 文件写入
fs.write(path, data, options, callback(err) => {})
path
路径,如无则新建
data
待写入的数据
options
配置,包含如{encoding, mode, flag}
等信息
callback(err)
回调,只包含 err
信息
const fs = require('fs')
const path = './life.txt'
const data = 'Life is difficult\rShow me the light'
const options = {}
const callback = (err) => {
console.error(err)
}
fs.writeFile(path, data, options, callback)