fs模块的其他方法

var fs = require('fs')

fs.existsSync(path)        检查一个文件是否存在
        var isExists = fs.existsSync('hello.txt')

fs.statSync(path)
fs.stat(path, callback)        获取文件的状态
    - 它会返回一个对象,这个对象中保存了当前对象状态的相关信息
    - 回调函数的形参有两个,一个err,一个stat,stat里面有几个方法
            size:        文件的大小
            isFile():        是否是一个文件
            isDirectory():        是否是一个文件夹

        fs.stat('hello.txt', function(err, stat, ){
            console.log(stat.size)        //文件的大小
        }) 

fs.unlinkSync(path)
fs.unlink(path, callback)        删除文件
        fs.unlink('hello.txt')

fs.readdirSync(path[, options])
fs.readdirSync(path[, options], callback)        读取一个目录的目录结构
    - files是一个字符串数组,每一个元素就是一个文件夹或文件的名字

        fs.readdir('.', function(err, files){            //'.' 代表当前目录
            if(!err){
                console.log(files)
            }
        })

fs.truncateSync(path, len)
fs.truncateSync(path, len, callback)        截断文件,将文件修改为指定大小字节,注意:一个汉字占3个字节
        fs.truncateSync('hello,txt', 3)

fs.mkdirSync(path[, mode])    
fs.mkdir(path[, mode], callback)            创建一个目录/文件夹
        fs.mkdir('helloDir')

fs.rmdirSync(path[, mode])    
fs.rmdir(path[, mode], callback)            删除一个目录/文件夹
        fs.rmdir('helloDir')

fs.renameSync(oldPath, newPath)    
fs.rename(oldPath, newPath, callback)            对文件夹进行重命名(相当于剪切)
- 参数:
        oldPath:    旧的路径
        newPath:    新的路径
        callback:        回调函数

        fs.rename('hello.txt', '你好.txt', function(err){
            if(!err){
                console.log('修改成功')
            }
        })
    
fs.watchFile(filename[, options], listener)            监视文件的修改(内部是每隔一段时间就检查一下是否发生变化)
- 参数:
    filename:        要监视的文件的名字
    options:        配置选项
        interval:        检查间隔
    listener:        回调函数,当文件发生变化时,回调函数会执行
        在回调函数中会有两个参数:
            curr:        当前文件的状态
            prev:        修改前文件的状态
            这两个对象都是stats对象(参考fs.stat)

        fs.watchFile('hello.txt', {interval : 1000}, function(curr, prev){
            console.log('修改前文件大小:' + prev.size)
            console.log('修改后(当前)文件大小:' + curr.size)
        })

 

posted @ 2022-03-05 14:23  蜘蛛流  阅读(77)  评论(0)    收藏  举报