Node.js study notes (2)#FS file system module

Table of contents

1. Introduction to the fs file system module

2. Import of fs file system module

3. Commonly used APIs of fs file system

1.fs.readFile()

2.fs.writeFile()

3.fs.stat()

4.fs.unlink()

5.fs.rename()

6.fs.open()

7.fs.appendFile()

8.fs.createWriteStream()


1. Introduction to the fs file system module

The fs (File System) file system module is one of the official built-in modules of Node.js. It provides a series of methods and attributes to meet the user's needs for operating files.

 

2. Import of fs file system module

We want to use the fs file system module. We need to import the fs module before using it. The following is how to import the fs module.

const fs =require('fs')

 

3. Commonly used APIs of fs file system

File system | Node.js v18.12.1 Documentation

The official document API lists all fs API operations. View them according to your own version. The official API of the node18 version is provided here. The following are some commonly used fs APIs that I have compiled

1.fs.readFile()

①Function:

Read the contents of the file at the specified path

②Usage:

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

Parameter 1: path required parameter <string> | <Buffer> | <URL> | <integer> to read the file storage path

Parameter 2: options can be default parameters

encoding <string> | <null>  The transcoding format used when writing files, the default is null

flag <string>   identifier, default is 'r'.

signal <AbortSignal>   allows aborting the ongoing read operation flag

Parameter 3: callback required parameter <Function>

err <Error> | <AggregateError>   reads the exception parameter err

data <string> | <Buffer> read success information data

③Code example:

const fs =require('fs')

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

2.fs.writeFile()

①Function:

Write content to the specified file. If the file does not exist, a new file will be created and the content will be written.

②Usage:

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

Parameter 1: file required parameter <string> | <Buffer> | <URL> | <integer> The path to store the file

Parameter 2: data required parameter <string> | <Buffer> | <TypedArray> | <DataView> | <Object> represents the written content data

Parameter 3: options can be default parameters <Object>

encoding <string> | <null>  The transcoding format used when writing files, the default is 'utf8'

mode <integer>   file mode, default is 0o666

flag <string>   identifier, default is 'w'.

signal <AbortSignal>   allows aborting the ongoing write operation flag

Parameter 4: callback required parameter <Function>

err <Error> | <AggregateError> writes the exception parameter err

③Code example:

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()

①Function:

Get information about the specified file

It is not recommended to use fs.stat() to check whether a file exists before calling fs.open(), fs.readFile(), or fs.writeFile(). Instead, user code should open/read/write the file directly and handle errors if the file is invalid.

If you want to check whether a file exists without operating on it, it is recommended to use fs.access().

②Usage:

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

Parameter 1: path required parameter <string> | <Buffer> | <URL> file path

Parameter 2: options can be default parameters <Object>

Whether the value returned by the bigint <Boolean> method is of bigint type, the default is false

Parameter 2: callback required parameter <Function>

err <Error> | <AggregateError> writes the exception parameter err

stats <fs.Stats> file information object

③Code example:

const fs =require('fs')

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

④Stats object

Property name

type

describe

dev

<number> | <bigint>

Numeric identifier of the device containing the file

mode

<number> | <bigint>

Bitfields describing the file type and mode

nlink

<number> | <bigint>

The number of hard links that exist in the file

uid

<number> | <bigint>

Numeric user identifier for the user who owns the file (POSIX)

gid

<number> | <bigint>

The numeric group identifier of the group owning file (POSIX)

rdev

<number> | <bigint>

Numeric device identifier if the file is considered "special"

blksize

<number> | <bigint>

File system block size for i/o operations

ino

<number> | <bigint>

File system specific "index node" number

size

<number> | <bigint>

File size (bytes)

blocks

<number> | <bigint>

Number of blocks allocated for the file

minusMs

<number> | <bigint>

The timestamp when the file was last accessed, measured in milliseconds since the POSIX Epoch

mtimeMs

<number> | <bigint>

The timestamp when the file was last modified, measured in milliseconds since the POSIX Epoch

ctimeMs

<number> | <bigint>

The timestamp of the file's most recent state modification, measured in milliseconds since the POSIX Epoch

birthtimeMs

<number> | <bigint>

Timestamp of file creation time, measured in milliseconds since POSIX Epoch

atime

<Date>

The timestamp when the file was last accessed

mtime

<Date>

The timestamp when the file was last modified

ctime

<Date>

The timestamp of the file’s most recent status change

birthtime

<Date>

File creation timestamp

⑤Stats method

method

Return type

effect

stats.isBlockDevice()

<Boolean>

Returns true if the fs.Stats object describes a block device

stats.isCharacterDevice()

<Boolean>

Returns true if the fs.Stats object describes a character device

stats.isDirectory()

<Boolean>

Returns true if the fs.Stats object describes a file system directory

stats.isFIFO()

<Boolean>

Returns true if the fs.Stats object describes a first-in-first-out pipe

stats.isFile()

<Boolean>

Returns true if fs.Stats describes a normal file

stats.isSocket()

<Boolean>

Returns true if the fs.Stats object describes a socket

stats.isSymbolicLink()

<Boolean>

Returns true if the fs.Stats object describes a symbolic link

This method is only valid when using fs.lstat()

4.fs.unlink()

①Function:

Remove specified file

②Usage:

fs.unlink(path, callback)

Parameter 1: path required parameter <string> | <Buffer> | <URL> file path

Parameter 2: callback required parameter <Function>

err <Error> | <AggregateError> writes the exception parameter err

③Code example:

const fs =require('fs')

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

5.fs.rename()

①Function:

Asynchronously rename the file with oldPath pathname to newPath pathname. If the newPath pathname already exists, the file will be overwritten. If there is a directory in newPath, an error will be raised.

②Usage:

fs.rename(oldPath, newPath, callback)

Parameter 1: oldPath required parameter <string> | <Buffer> | <URL> original path of the file

Parameter 2: newPath required parameter <string> | <Buffer> | <URL> file rename target path

Parameter 3: callback required parameter <Function>

err <Error> | <AggregateError> writes the exception parameter err

③Code example:

const fs =require('fs')

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

6.fs.open()

①Function:

Before performing file operations, you need to use fs.open() to open the file, then use the file descriptor fd to call the callback, and perform read fs.read() and write fs.wrtie() operations in the callback function, etc.

②Usage:

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

Parameter 1: path required parameter <string> | <Buffer> | <URL> file path

Parameter 2: flags required parameter <string> | <number>   file operation identifier

Parameter 3: mode can be the default parameter <string> | <integer> file mode, default 0o666

Parameter 4: callback required parameter <Function>

err <Error> File opening exception parameter err

fd <integer> file descriptor fd

③Code example:

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 identifier correspondence table

identifier

effect

r

Open file in read mode

r+

Open file in read-write mode

rs

Open and read the file using synchronous mode. Instructs the operating system to ignore the local file system cache

rs+

Open, read and write files synchronously. Note: This is not a blocking operation that puts fs.open into synchronous mode. If you want synchronous mode use fs.openSync()

w

Open the file in read mode, creating it if it does not exist

wx

Like 'w' mode, returns failure if the file exists

wx+

Like ' w+ ' mode, returns failure if file exists

a

Open the file in append mode, creating it if it does not exist

ax

Like 'a' mode, returns failure if file exists

a+

Open the file in read-append mode, creating it if it does not exist

ax+

Like the 'a+' mode, if the file exists, a failure mode is returned. It is used to set permissions for the file when creating the file. The default is 0o666.

7.fs.appendFile()

①Function:

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

②用法:

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> The number of bytes to start writing from

fs  <Object> | <null> Provides a file with a writable stream. The default is null.

③Code example:

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')

Guess you like

Origin blog.csdn.net/weixin_42214717/article/details/127864269