文件操作相关API
const fs = require('fs')
- fs.readFile(path[, options], callback) 读取文件
- path | | 文件路路径
- callback 回调函数
fs.readFile('./hello.txt','utf8',(err,data) => {
if(err) throw err;
console.log(data);
})
- s.writeFile(file, data[, options], callback) 写入文件
- file | | | 文件名或文件描述符。
- data | | | 写入的数据
- options |
- encoding | 写入字符串串的编码格式 默认值: ‘utf8’ 。
- mode 文件模式(权限) 默认值: 0o666 。
- flag 参阅⽀支持的文件系统标志。默认值: ‘w’ 。
- callback 回调函数
err
fs.writeFile('./hello.txt','this is a test',err => {
if(err) throw err;
console.log('写⼊入成功');
})
- fs.appendFile(path, data[, options], callback) 追加数据到文件
- path | | | 文件名或文件描述符。
- data | 追加的数据
- options |·
- encoding | 写入字符串串的编码格式 默认值: ‘utf8’ 。
- mode 文件模式(权限) 默认值: 0o666 。
- flag 参阅支持的文件系统标志。默认值: ‘a’
- callback 回调函数
const buf = Buffer.from('hello world!')
fs.appendFile('./hello.txt',buf,(err) => {
if(err) throw err;
console.log('追加成功');
})
- fs.stat(path[, options], callback) 获取⽂文件信息,判断⽂文件状态(是⽂文件还是文件夹)
- path | |
- options
- bigint 返回的 fs.Stats 对象中的数值是否应为 bigint 型。默认值: false
- callback
- err
- stats <fs.Stats> 文件信息
fs.stat('./hello.txtt',(err,stats) => {
if(err){
console.log('文件不不存在');
return;
}
console.log(stats);
console.log(stats.isFile());
console.log(stats.isDirectory());
})
- fs.rename(oldPath, newPath, callback) 重命名文件
- oldPath | | 旧⽂文件路路径名字
- newPath | | 新⽂文件路路径名字
- callback 回调函数
fs.rename('./hello.txt','./test.txt',err => {
if(err) throw err;
console.log('重命名成功');
})
- fs.unlink(path, callback) 删除⽂文件
fs.unlink('./test.txt',err => {
if(err) throw err;
console.log('删除成功');
})
文件夹操作相关API
- fs.mkdir(path[, options], callback) 创建⽂文件夹
- path | |
- options |
- recursive 是否递归创建 默认值: false 。
- mode 文件模式(权限)Windows 上不不支持。默认值: 0o777 。
- callback
const fs =require('fs');
// fs.mkdir('./a',err => {
// if(err) throw err;
// console.log('创建文件夹成功');
// })
fs.mkdir('./b/c',{
recursive:true
},err => {
if(err) throw err;
console.log('创建文件夹成功');
})
- fs.readdir (path[, options], callback) 读取文件夹
- path | |
- options |
- encoding 默认值: ‘utf8’ 。
- withFileTypes 默认值: false
- callback
- err
- files <string[]> | <buffer[]> | <fs.Dirent[]>
fs.readdir('./',{
encoding:'buffer', //设置buffer,files返回文件名为buffer对象
withFileTypes:true //单上文件类型
},(err,files) => {
if(err) throw err;
console.log(files)
})
- fs.rmdir(path[, options], callback) 删除⽂文件夹
- path | |
- options
- maxRetries 重试次数。出现这类错误 EBUSY 、 EMFILE 、 ENFILE 、 ENOTEMPTY 或
者EPERM ,每⼀一个重试会根据设置的重试间隔重试操作。如果 recursive不不为true则忽略略. 默认值: 0。
- retryDelay 重试的间隔,如果 recursive 不不为true则忽略略. 默认值: 100 。
- recursive 如果为 true ,则执⾏行行递归的⽬目录删除。在递归模式中,如果 path 不不存在则不不报告错误,并且在失败时重试操作。默认值: false 。
fs.rmdir('./b',{
recursive:true
},err => {
if(err) throw err;
console.log('删除⽂文件夹成功');
})
npm install chokidar --save-dev
- Chokidar.watch(path,[options])
chokidar.watch('./',{
ignored:'./node_modules'
}).on('all',(event,path) => {
console.log(event,path)
})