更新于 

fs其他方法

单个文件操纵

验证路径是否存在
1
2
let isExits = fs.existsSync('hello.txt');
console.log(isExits) //true
  • fs.exists(path, callback)
    • 已经删除的方法,因为验证功能一般需要立即获取到结果,无需引入异步
  • fs.existesSync(path)
获取文件信息
1
2
3
fs.stat('hello.txt', function (err,stats) {
console.log(stats);
})

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Stats {
dev: 3932212942,
mode: 33206,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
blksize: 4096,
ino: 5910974511137847,
size: 46,
blocks: 0,
atimeMs: 1679821361534.1057,
mtimeMs: 1679821361534.1057,
ctimeMs: 1679821361534.1057,
birthtimeMs: 1679818224344.4,
atime: 2023-03-26T09:02:41.534Z,
mtime: 2023-03-26T09:02:41.534Z,
ctime: 2023-03-26T09:02:41.534Z,
birthtime: 2023-03-26T08:10:24.344Z
}
  • fs.stat(path, callback)
    • 获取文件的状态
    • 返回一个对象,该对象保存了当前对象状态的相关信息
  • fs.statSync(path)
删除文件
1
fs.unlinkSync('./hello_copy_stream.txt');
  • fs.unlink(path, callback)

  • fs.unlinkSync(path)

截断文件

将文件截断为指定大小

1
fs.truncateSync('hello_copy.txt', 4);
  • fs.truncate(path, len,callback)

  • fs.truncateSync(path, len)

监视文件更改写入
1
2
3
fs.watchFile('hello.txt', function () {
console.log('hello.txt change')
})
  • fs.watchFile(filename[, options], listener)
    • options
      • interval 间隔,默认5000ms
    • listener参数
      • curr stat对象,表示当前文件的状态
      • prev stat对象,表示修改前文件的状态

目录操作

列出目录
1
2
3
fs.readdir('.', function (err, data) {
console.log(data);
})

运行结果

1
2
3
4
5
6
7
8
9
10
11
[
'asynch_write.js',
'hello.txt',
'hello_copy.txt',
'main.js',
'other_func.js',
'read.js',
'simple_write.js',
'stream_read.js',
'stream_write.js'
]
  • fs.readdir(path[, options], callback)
    • callback
      • err
      • files 数组 元素为目录中文件名
  • fs.readdirSync(path[, options])
建立目录
1
fs.mkdirSync('hello');
  • fs.mkdir(path[, mode], callback)
  • fs.mkdirSync(path[, mode])
删除目录
1
fs.rmdirSync('hello');
  • fs.rmdir(path, callback)
  • fs.rmdirSync(path)
重命名文件和目录
1
fs.renameSync('hello_copy.txt','hello2.txt')

rename还能通过绝对路径实现文件的剪切功能

1
fs.renameSync('hello_copy.txt','D:\\hello2.txt')
  • fs.rename(oldPath, newPath, callback)
  • fs.renameSync(oldPath, newPath)