Node.js学习笔记(二)#FS文件系统模块

目录

一、fs文件系统模块简介

二、fs文件系统模块导入

三、fs文件系统常用API

1.fs.readFile()

2.fs.writeFile()

3.fs.stat()

4.fs.unlink()

5.fs.rename()

6.fs.open()

7.fs.appendFile()

8.fs.createWriteStream()


一、fs文件系统模块简介

fs(File System)文件系统模块是Node.js官方内置的模块之一,提供了一系列方法和属性,用来满足用户对操作文件的需求。

二、fs文件系统模块导入

我们要用到fs文件系统模块,需要在使用前先导入fs模块,以下是导入fs模块的方法

const fs =require('fs')

三、fs文件系统常用API

File system | Node.js v18.12.1 Documentation

官方文档API列出了所有fs的API操作,根据自己的版本来进行查看,这里提供的是node18版本的官方API。以下是我整理出来的一些常用的fs API

1.fs.readFile()

①作用:

读取指定路径的文件内容

②用法:

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

参数1:path 必填参数 <string> | <Buffer> | <URL> | <integer> 读取文件存放路径

参数2:options 可缺省参数

encoding <string> | <null>  写入文件时采用的转码格式,默认为 null

flag <string>  标识符,默认为 'r'.

signal <AbortSignal>  允许中止正在进行的读取操作标识

参数3:callback 必填参数 <Function>

err <Error> | <AggregateError>  读取异常参数err

data <string> | <Buffer> 读取成功信息data

③代码示例:

const fs =require('fs')

fs.readFile('./target.txt','utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});
//输出 Hello Node.js!!!!!

2.fs.writeFile()

①作用:

向指定文件中写入内容,若文件不存在,则会新建文件然后写入内容

②用法:

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

参数1:file 必填参数 <string> | <Buffer> | <URL> | <integer> 存放文件的路径

参数2:data 必填参数 <string> | <Buffer> | <TypedArray> | <DataView> | <Object> 表示写入的内容数据

参数3:options 可缺省参数 <Object>

encoding <string> | <null>  写入文件时采用的转码格式,默认为 ‘utf8’

mode <integer>  文件模式,默认为 0o666

flag <string>  标识符,默认为 'w'.

signal <AbortSignal>  允许中止正在进行的写入操作标识

参数4:callback 必填参数 <Function>

err <Error> | <AggregateError> 写入异常参数err

③代码示例:

const fs =require('fs')

const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data,'utf8', (err) => {
  if (err) throw err;
  console.log('文件已保存!');
});
//输出文件 message.txt -- Hello Node.js
//输出文件已保存!

3.fs.stat()

①作用:

获取指定文件的信息

不建议在调用 fs.open() 、fs.readFile() 或 fs.writeFile() 之前使用 fs.stat() 检查一个文件是否存在。 作为替代,用户代码应该直接打开/读取/写入文件,当文件无效时再处理错误。

如果要检查一个文件是否存在且不操作它,推荐使用 fs.access()。

②用法:

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

参数1:path 必填参数 <string> | <Buffer> | <URL> 文件的路径

参数2:opitions 可缺省参数 <Object>

bigint <Boolean> 方法返回的数值是否为bigint类型,默认false

参数2:callback 必填参数 <Function>

err <Error> | <AggregateError> 写入异常参数err

stats <fs.Stats> 文件信息对象

③代码示例:

const fs =require('fs')

fs.stat('target.txt', (err, stats) => {
    if (err) throw err;
    console.log(stats);
});
//输出stats对象

④Stats对象

属性名称

类型

描述

dev

<number> | <bigint>

包含文件的设备的数字标识符

mode

<number> | <bigint>

描述文件类型和模式的位域

nlink

<number> | <bigint>

文件存在的硬链接数

uid

<number> | <bigint>

用户拥有文件(POSIX)的数字用户标识符

gid

<number> | <bigint>

组拥有文件(POSIX)的数字组标识符

rdev

<number> | <bigint>

如果文件被视为“特殊”时的数字设备标识符

blksize

<number> | <bigint>

i/o操作的文件系统块大小

ino

<number> | <bigint>

文件系统特定的“索引节点”编号

size

<number> | <bigint>

文件的大小(字节)

blocks

<number> | <bigint>

为文件分配的块数

atimeMs

<number> | <bigint>

文件最近一次被访问的时间戳,以POSIX Epoch以来的毫秒数计算

mtimeMs

<number> | <bigint>

文件最近一次修改的时间戳,以POSIX Epoch以来的毫秒数计算

ctimeMs

<number> | <bigint>

文件最近一次状态修改的时间戳,以POSIX Epoch以来的毫秒数计算

birthtimeMs

<number> | <bigint>

文件创建时间的时间戳,以POSIX Epoch以来的毫秒数计算

atime

<Date>

文件最近一次被访问的时间戳

mtime

<Date>

文件最近一次修改的时间戳

ctime

<Date>

文件最近一次状态变动的时间戳

birthtime

<Date>

文件创建的时间戳

⑤Stats方法

方法

返回类型

作用

stats.isBlockDevice()

<Boolean>

如果fs.Stats对象描述了一个块设备,则返回true

stats.isCharacterDevice()

<Boolean>

如果fs.Stats对象描述了一个字符设备,则返回true

stats.isDirectory()

<Boolean>

如果fs.Stats对象描述一个文件系统目录,则返回true

stats.isFIFO()

<Boolean>

如果fs.Stats对象描述了一个先进先出管道,则返回true

stats.isFile()

<Boolean>

如果fs.Stats描述了一个正常的文件,则返回true

stats.isSocket()

<Boolean>

如果fs.Stats对象描述一个socket,则返回true

stats.isSymbolicLink()

<Boolean>

如果fs.Stats对象描述一个符号链接,则返回true

这个方法只有使用fs.lstat()时才有效

4.fs.unlink()

①作用:

移除指定的文件

②用法:

fs.unlink(path, callback)

参数1:path 必填参数 <string> | <Buffer> | <URL> 文件的路径

参数2:callback 必填参数 <Function>

err <Error> | <AggregateError> 写入异常参数err

③代码示例:

const fs =require('fs')

fs.unlink('message.txt', (err) => {
    if (err) throw err;
    console.log('message.txt已被删除');
});
//移除message.txt
//输出message.txt已被删除

5.fs.rename()

①作用:

将oldPath路径名的文件异步重命名为newPath路径名。若newPath路径名已存在,则会覆盖该文件。若newPath中有一个目录,则会引发错误。

②用法:

fs.rename(oldPath, newPath, callback)

参数1:oldPath 必填参数 <string> | <Buffer> | <URL> 文件原始路径

参数2:newPath 必填参数 <string> | <Buffer> | <URL> 文件重命名靶路径

参数3:callback 必填参数 <Function>

err <Error> | <AggregateError> 写入异常参数err

③代码示例:

const fs =require('fs')

fs.rename('oldpath.txt', 'newpath.txt', (err) => {
    if (err) throw err
    console.log('移动文件成功')
})
//输出 移动文件成功

6.fs.open()

①作用:

在进行文件操作前,需使用fs.open()打开文件,然后使用文件描述符fd调用回调,在回调函数中进行读fs.read()写fs.wrtie()操作等

②用法:

fs.open(path, flags[, mode], callback)

参数1:path 必填参数 <string> | <Buffer> | <URL> 文件的路径

参数2:flags 必填参数 <string> | <number>  文件操作标识符

参数3:mode 可缺省参数 <string> | <integer> 文件模式,默认0o666

参数4:callback 必填参数 <Function>

err <Error> 文件打开异常参数err

fd <integer> 文件描述符fd

③代码示例:

const fs = require('fs')

fs.open('open.txt', 'w+', (err, fd) => {
    if (err) throw err;
    fs.write(fd, Buffer.from('Hello Nodejs'),0, 12, (err, bytesWritten, buffer) => {
        if (err) throw err;
        console.log('写入成功')
    })
})
//输出写入成功

④flags标识符对应表

标识符

作用

r

以读取模式打开文件

r+

以读写模式打开文件

rs

使用同步模式打开并读取文件。指示操作系统忽略本地文件系统缓存

rs+

以同步的方式打开,读取并写入文件。注意:这不是让fs.open变成同步模式的阻塞操作。如果想要同步模式请使用fs.openSync()

w

以读取模式打开文件,如果文件不存在则创建

wx

和 ' w ' 模式一样,如果文件存在则返回失败

wx+

和 ' w+ ' 模式一样,如果文件存在则返回失败

a

以追加模式打开文件,如果文件不存在则创建

ax

和 ' a ' 模式一样,如果文件存在则返回失败

a+

以读取追加模式打开文件,如果文件不存在则创建

ax+

和 ' a+ ' 模式一样,如果文件存在则返回失败 mode,用于创建文件时给文件制定权限,默认0o666

7.fs.appendFile()

①作用:

向指定文件追加数据,若文件还没有创建,则创建文件并追加数据

②用法:

fs.appendFile(path, data[, options], callback)

参数1:path 必填参数 <string> | <Buffer> | <URL> | <number>  文件的路径

参数2:data 必填参数 <string> | <Buffer> 表示追加的内容数据

参数3:options 可缺省参数 <Object>

encoding <string> | <null> 追加写入文件时采用的转码格式,默认为'utf8'

mode <integer> 追加写入文件时文件模式,默认为0o666

flag <string> 追加写入文件时文件操作标识符,默认为 'a'

参数4:callback 必填参数 <Function>

err <Error> 追加异常参数err

③代码示例:

const fs = require('fs')

fs.appendFile('message.txt', 'data to append', (err) => {
    if (err) throw err;
    console.log('The "data to append" was appended to file!');
});
//输出message.txt -- Hello Node.jsdata to append
//输出The "data to append" was appended to file!

8.fs.createWriteStream()

①作用:

创建可写流fs.WriteStream类对象,可进行写入操作

②用法:

fs.createWriteStream(path[, options])

参数1:path 必填参数 <string> | <Buffer> | <URL> 文件的路径

参数2:options 可缺省参数 <string> | <Object>

flags <string> 标识符,默认为'w'

encoding <string> 转码类型,默认为'utf8'

fd <integer> | <FileHandle> 文件描述符,默认为null

mode <integer> 模式,默认为0o666

autoClose <boolean> 写完是否自动关闭,默认为true

emitClose <boolean> 是否emit关闭事件,默认为true

start <integer> 从第几个字节开始写入

fs <Object> | <null> 提供可写流的文件,默认为null

③代码示例:

const fs = require('fs')

//创建可写流 fs.WriteStream 类的对象,继承自 <stream.Writable>
const writer = fs.createWriteStream('a.txt', {
    flags: 'w',//标识符默认为'w'
    encoding: 'utf8', // 转码类型默认为'utf8'
    fd : null,//文件描述符,默认为null
    mode: 0o666,//模式,默认为0o666
    autoClose: true,// 写完是否自动关闭,默认为true
    start:0 //从第0个字节开始写
})

//写入数据到流
writer.write('Hello Nodejs')

猜你喜欢

转载自blog.csdn.net/weixin_42214717/article/details/127864269