Node.js核心模块-fs文件系统

fs是file-system的简写,文件系统的意思。在Node中如果想要进行文件操作,就必须引入fs这个核心模块。

引入

const fs = require('fs')

fs.readFile(path[, options], callback)

  • path:要读取的文件路径
  • options:可选
    • encoding,指定字符编码
  • callback:回调函数,有两个参数,err和data
    • err:读取失败返回错误对象,读取成功返回null
    • data:读取成功返回读到的数据,否则返回undefined

比如文件路径错误时:err打印出错误对象,data为undefined

const fs = require('fs')

fs.readFile('./1.txt', function (err, data) {
    console.log(err)
    console.log(data)
})

//{ [Error: ENOENT: no such file or directory, open './1.txt'] errno: -2, code: 'ENOENT', syscall: 'open', path: './1.txt' }
// undefined

文件路径正常且读取成功时:

// null
// <Buffer 68 65 6c 6c 6f>

1.txt中文件读取成功并返回了buffer。文件中原本存储的是二进制数据0和1,二进制转为16进制即buffer。如果想转成我们认识的字符,可以通过toString()方法:

const fs = require('fs')

fs.readFile('./1.txt', function (err, data) {
    console.log(data.toString())
})

// hello

或者通过字符编码

const fs = require('fs')

fs.readFile('./1.txt', 'utf8', function (err, data) {
    console.log(data)
})

// hello

在读文件时建议做容错,避免读取错误data取不到报错

fs.readFile('./1.txt', function (err, data) {
    if (err) {
        console.log(err)
    } else {
        console.log(data.toString())
    }
})

fs.writeFile(file, data[, options], callback)

  • file:要写入的文件路径
  • data:要写入的内容
  • options:可选
  • callback:回调函数
    • err:写入成功时为null,写入错误时为错误对象
fs.writeFile('./2.txt', '你好', function (err) {
    if (err) {
        console.log(err)
    } else {
        console.log('写入成功')
    }
})

如果当前目录中有2.txt,会写入“你好”,如果当前目录中没有这个文件,会创建文件并写入

fs.readdir(path[, options], callback)

  • path:路径
  • option:可选
  • callback:回调函数
    • err
    • files 目录中文件名的数组

读取目录的内容

const fs = require('fs')
fs.readdir('/Users/lianglanlan/Desktop/code/study/node/www', (err, files) => {
    if (err) {
        return console.log('目录不存在')
    }
    console.log(files)  //[ 'a.txt', 'apple', 'index.html', 'index1.html' ]
})

 fs.existsSync(path)

  • path:路径
  • 返回值:布尔类型

如果路径存在,返回true,否则返回false

const fs = require('fs')
if (fs.existsSync('./1.txt')) {
    console.log('该路径已存在');
}

fs.unlink(path,callback)

  • path:路径
  • callback:回调函数
    • err

异步地删除文件或符号链接。

const fs = require('fs')
fs.unlink('./1.txt', err => {
    if (err) {
        console.log(err)
    } else {
        console.log('文件已被删除')
    }
})
//删除了同目录中的1.txt

如果path不存在,会报错no such file or directory

如果path为目录路径,会报错 operation not permitted

fs.unlinkSync(path)

同步的fs.unlink(),返回undefined

fs.symlink(target,path[,type],callback)

  • target
  • path
  • type  仅在windows可用
  • callback
    • err 异常参数

会创建名为path的链接,该链接指向target

const fs = require('fs')
fs.symlink('./index.html', './indextwo.html', err => {
    console.log(err)
})

//在当前目录创建了indextwo.html,指向index.html。当index.html修改时,indextwo.html也会同步修改

fs.symlinkSync(target,path[,type])

同步的fs.symlink,返回undefined

fs.stat(path[,options],callback)

返回fs.stats类

fs.statSync(path[, options])

  • path:路径

同步的fs.stat。返回fs.stats类

fs.lstat(path[options],callback)

与fs.stat相同。只是如果path是符号链接,则查看的是链接自身,而不是它指向的文件

fs.stats类

提供关于文件的信息

stats.isDirectory()

如果是目录,则返回true

stats.isSymbolicLink()

如果是符号链接,则返回true

stats.mtime

上次修改此文件的时间戳

const fs = require('fs')
const fsStatus = fs.statSync('./index.html')
console.log(fsStatus.mtime) //2020-12-03T10:32:52.276Z

stats.size

文件的大小,以字节为单位

const fs = require('fs')
console.log(fs.statSync('./index.html').size) //866

fs.createReadStream(path[,option])

  • path:string | buffer | url
  • options:
    • autoClose:默认值true。如果为false,即使发生错误,文件描述符也不会被关闭。如果为true,则当error或end事件时,文件描述符会被自动关闭。

返回fs.ReadStream实例

fs.createWriteStream(path[,option])

返回fs.WriteStream实例

fs.ReadStream类

继承自stream.readable

fs.WriteStream类

继承自stream.writeable

fs.mkdirSync(path[,options])

  • path:路径
  • options
    • recursive:布尔,默认值false

同步地创建目录。如果recursive为true,返回创建的目录路径。否则返回undefined。

fs.copyFile(src,dest[,mode],callback)

  • src: 要拷贝的源文件名
  • dest:拷贝操作的目标文件名。如果已经存在,会进行覆盖
  • mode:用于拷贝操作的修饰符,默认值0
  • callback
    • err:异常
fs.copyFile('./index.html', './index2.html', err => {
    console.log(err)
})
原文地址:https://www.cnblogs.com/lianglanlan/p/12092357.html