module fs
The fs module is a file system operation module. It provides disk I/O operations such as reading files, writing files, opening files, closing files, changing file permissions, etc., and supports both synchronous and asynchronous usage. The fs module also provides a file monitor function, which can monitor changes in files and directories in the file system and call back the specified function.
For example, to read a file in fibjs, you can use the readFile method of the fs module:
1
2var fs = require('fs');
var content = fs.readFile('/path/to/file');
If you want to read the file asynchronously, you can do it through a callback:
1
2
3
4
5var fs = require('fs');
fs.readFile('/path/to/file', function(err, data) {
if (err) throw err;
console.log(data);
});
Similarly, if you want to write to a file, you can use the writeFile method of the fs module:
1
2
3var fs = require('fs');
var content = 'hello, world!';
fs.writeFile('/path/to/file', content);
If you want to write a file asynchronously, you can do it through a callback:
1
2
3
4
5
6var fs = require('fs');
var content = 'hello, world!';
fs.writeFile('/path/to/file', content, function(err) {
if (err) throw err;
console.log('File saved.');
});
In addition to reading and writing files, the fs module also provides a series of other file system operations, such as creating directories, modifying file permissions, querying file status, etc.
Some points to note:
- Running
fs.watch(filename)
will return a value inherited fromEventEmitterwatcher, which supports three events: 'change', 'changeonly', 'renameonly' fs.watchFile(target)
andfs.unwatchFile(target)
can still be used in pairsfs.watchFile(target)
will return a value inherited fromEventEmitterofStatsWatcherObject, callfs.unwatchFile(target)
is equivalent to callStatsWatcher.close()
.- Because uv is implemented on Linux,
fs.watch
therecursive
option is only stably supported in win32/darwin. You can still try to use it in Linuxfs.watch('/[path](path.md)/to', { recursive: true }, handler)
, but you may find thathandler
the timing of being called back is different from what you expected.
object
constants
Constant objects of the fs module
1fs_constants fs.constants;
static function
exists
Query whether the specified file or directory exists
1static Boolean fs.exists(String path) async;
Call parameters:
- path: String, specify the path to be queried
Return results:
- Boolean, returns True to indicate that the file or directory exists
access
Query the user's permissions on the specified file
1
2static fs.access(String path,
Integer mode = 0) async;
Call parameters:
- path: String, specify the path to be queried
- mode: Integer, specifies the query permission, the default is whether the file exists
link
Create a hard link file, this method is not supported under windows
1
2static fs.link(String oldPath,
String newPath) async;
Call parameters:
- oldPath: String, source file
- newPath: String, the file to be created
unlink
Delete specified file
1static fs.unlink(String path) async;
Call parameters:
- path: String, specifies the path to be deleted
mkdir
Create a directory
1
2static fs.mkdir(String path,
Integer mode = 0777) async;
Call parameters:
- path: String, specify the directory name to be created
- mode: Integer, specifies file permissions, Windows ignores this parameter, default value: 0777
Create a directory
1
2static fs.mkdir(String path,
Object opt) async;
Call parameters:
- path: String, specify the directory name to be created
- opt: Object, specify creation parameters
Creation parameters can contain the following values:
1
2
3
4{
recursive: false, // specify whether parent directories should be created. Default: false
mode: 0777 // specify the file mode. Default: 0777
}
rmdir
Delete a directory
1static fs.rmdir(String path) async;
Call parameters:
- path: String, specifies the directory name to be deleted
rename
Rename a file
1
2static fs.rename(String from,
String to) async;
Call parameters:
- from: String, specifies the file to be renamed
- to: String, specifies the new file name to be modified
copyFile
Copy src to dest. By default, if dest already exists, it is overwritten.
1
2
3static fs.copyFile(String from,
String to,
Integer mode = 0) async;
Call parameters:
- from: String, specifies the source file name to be copied
- to: String, specifies the name of the target file to be copied.
- mode: Integer, specifies the modifier of the copy operation, the default is 0
mode is an optional integer specifying the behavior of the copy operation. You can create a mask consisting of a bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL |fs.constants.COPYFILE_FICLONE).
- fs.constants.COPYFILE_EXCL - If dest already exists, the copy operation will fail.
- fs.constants.COPYFILE_FICLONE - The copy operation will attempt to create a copy-on-write link. If the platform does not support copy-on-write, a fallback copy mechanism is used.
- fs.constants.COPYFILE_FICLONE_FORCE - The copy operation will attempt to create a copy-on-write link. If the platform does not support copy-on-write, the copy operation will fail.
chmod
Set access permissions for the specified file. Windows does not support this method.
1
2static fs.chmod(String path,
Integer mode) async;
Call parameters:
- path: String, file specifying the operation
- mode: Integer, specifies the set access permissions
lchmod
Set the access permissions of the specified file. If the file is a soft link, the permissions pointing to the file will not be changed. It is only available on macOS and BSD series platforms.
1
2static fs.lchmod(String path,
Integer mode) async;
Call parameters:
- path: String, file specifying the operation
- mode: Integer, specifies the set access permissions
chown
Set the owner of the specified file. Windows does not support this method.
1
2
3static fs.chown(String path,
Integer uid,
Integer gid) async;
Call parameters:
- path: String, file specifying settings
- uid: Integer, file owner user id
- gid: Integer, file owner group id
lchown
Set the owner of the specified file. If the specified file is a soft link, the owner of the file it points to will not be changed. Windows does not support this method.
1
2
3static fs.lchown(String path,
Integer uid,
Integer gid) async;
Call parameters:
- path: String, file specifying settings
- uid: Integer, file owner user id
- gid: Integer, file owner group id
stat
Query the basic information of the specified file
1static Stat fs.stat(String path) async;
Call parameters:
- path: String, specifies the file to be queried
Return results:
- Stat, returns the basic information of the file
lstat
Query the basic information of the specified file. Different from stat, whenpathWhen it is a soft link, the information returned will be the information of this soft link instead of the information of the pointed file.
1static Stat fs.lstat(String path) async;
Call parameters:
- path: String, specifies the file to be queried
Return results:
- Stat, returns the basic information of the file
fstat
Query the basic information of the specified file
1static Stat fs.fstat(FileHandle fd) async;
Call parameters:
- fd:FileHandle, file descriptor object
Return results:
- Stat, returns the basic information of the file
readlink
Read the specified soft link file. This method is not supported under Windows.
1static String fs.readlink(String path) async;
Call parameters:
- path: String, specifies the soft link file to read
Return results:
- String, returns the file name pointed to by the soft link
realpath
Returns the absolute path of the specified path. If the specified path contains a relative path, it will also be expanded.
1static String fs.realpath(String path) async;
Call parameters:
- path: String, specifies the path to read
Return results:
- String, returns the processed absolute path
symlink
Create soft link file
1
2
3static fs.symlink(String target,
String linkpath,
String type = "file") async;
Call parameters:
- target: String, target file, which can be a file, directory, or non-existent path
- linkpath: String, the soft link file to be created
- type: String, the type of soft connection created, the optional types are 'file', 'dir', 'junction', the default is 'file', this parameter is only valid on windows, when it is 'junction', the target will be created The path linkpath must be an absolute path, and the target will be automatically converted into an absolute path.
truncate
Modify the file size. If the specified length is greater than the source file size, it will be filled with '\0', otherwise the excess file content will be lost.
1
2static fs.truncate(String path,
Integer len) async;
Call parameters:
- path: String, specifies the path of the modified file
- len: Integer, specifies the size of the modified file
read
Read the file content according to the file descriptor
1
2
3
4
5static Integer fs.read(FileHandle fd,
Buffer buffer,
Integer offset = 0,
Integer length = 0,
Integer position = -1) async;
Call parameters:
- fd:FileHandle, file descriptor object
- buffer:Buffer, the read result is written toBufferobject
- offset: Integer,BufferWrite offset, default is 0
- length: Integer, the number of bytes read from the file, the default is 0
- position: Integer, file reading position, default is the current file position
Return results:
- Integer, the actual number of bytes read
fchmod
Change the file mode based on the file descriptor. Valid only on POSIX systems.
1
2static fs.fchmod(FileHandle fd,
Integer mode) async;
Call parameters:
- fd:FileHandle, file descriptor object
- mode: Integer, the mode of the file
fchown
Depending on the file descriptor, change the owner. Valid only on POSIX systems.
1
2
3static fs.fchown(FileHandle fd,
Integer uid,
Integer gid) async;
Call parameters:
- fd:FileHandle, file descriptor object
- uid: Integer, user id
- gid: Integer, group id
fdatasync
Synchronize data to disk based on file descriptor
1static fs.fdatasync(FileHandle fd) async;
Call parameters:
- fd:FileHandle, file descriptor object
fsync
Synchronize data to disk based on file descriptor
1static fs.fsync(FileHandle fd) async;
Call parameters:
- fd:FileHandle, file descriptor object
readdir
Read file information from the specified directory
1static NArray fs.readdir(String path) async;
Call parameters:
- path: String, specifies the directory to be queried
Return results:
- NArray, returns the file information array of the directory
Read file information from the specified directory
1
2static NArray fs.readdir(String path,
Object opts = {}) async;
Call parameters:
- path: String, specifies the directory to be queried
- opts: Object, specify parameters
Return results:
- NArray, returns the file information array of the directory
The options supported by the parameter opts are as follows:
1
2
3{
"recursive": false // specify whether all subdirectories should be watched or only the current directory
}
openFile
Open a file for reading, writing, or both
1
2static SeekableStream fs.openFile(String fname,
String flags = "r") async;
Call parameters:
- fname: String, specify the file name
- flags: String, specifies the file opening method, the default is "r", read-only mode
Return results:
- SeekableStream, returns the open file object
The supported methods of parameter flags are as follows:
- 'r' Read-only mode, throws an error if the file does not exist.
- 'r+' read and write mode, throw an error if the file does not exist.
- 'w' is write-only mode. If the file does not exist, it will be automatically created. If it exists, it will be cleared.
- 'w+' reading and writing mode, the file will be automatically created if it does not exist.
- 'a' only writes the add method, and the file will be automatically created if it does not exist.
- 'a+' read-write add mode, the file will be created automatically if it does not exist.
open
open file descriptor
1
2
3static FileHandle fs.open(String fname,
String flags = "r",
Integer mode = 0666) async;
Call parameters:
- fname: String, specify the file name
- flags: String, specifies the file opening method, the default is "r", read-only mode
- mode: Integer, when creating a file, specify the file mode, default 0666
Return results:
- FileHandle, returns the open file descriptor
The supported methods of parameter flags are as follows:
- 'r' Read-only mode, throws an error if the file does not exist.
- 'r+' read and write mode, throw an error if the file does not exist.
- 'w' is write-only mode. If the file does not exist, it will be automatically created. If it exists, it will be cleared.
- 'w+' reading and writing mode, the file will be automatically created if it does not exist.
- 'a' only writes the add method, and the file will be automatically created if it does not exist.
- 'a+' read-write add mode, the file will be created automatically if it does not exist.
close
close file descriptor
1static fs.close(FileHandle fd) async;
Call parameters:
- fd:FileHandle, file descriptor object
openTextStream
Open a text file for reading, writing, or both
1
2static BufferedStream fs.openTextStream(String fname,
String flags = "r") async;
Call parameters:
- fname: String, specify the file name
- flags: String, specifies the file opening method, the default is "r", read-only mode
Return results:
- BufferedStream, returns the open file object
The supported methods of parameter flags are as follows:
- 'r' Read-only mode, throws an error if the file does not exist.
- 'r+' read and write mode, throw an error if the file does not exist.
- 'w' is write-only mode. If the file does not exist, it will be automatically created. If it exists, it will be cleared.
- 'w+' reading and writing mode, the file will be automatically created if it does not exist.
- 'a' only writes the add method, and the file will be automatically created if it does not exist.
- 'a+' read-write add mode, the file will be created automatically if it does not exist.
readTextFile
Open a text file and read its contents
1static String fs.readTextFile(String fname) async;
Call parameters:
- fname: String, specify the file name
Return results:
- String, returns the text content of the file
readFile
Open the file and read the contents
1
2static Variant fs.readFile(String fname,
String encoding = "") async;
Call parameters:
- fname: String, specify the file name
- encoding: String, specifies the decoding method, no decoding is performed by default
Return results:
- Variant, returns the text content of the file
Open the file and read the contents
1
2static Variant fs.readFile(String fname,
Object options) async;
Call parameters:
- fname: String, specify the file name
- options: Object, specifies read options
Return results:
- Variant, returns the text content of the file
The options supported by options are as follows:
1
2
3{
"encoding": "utf8" // specify the encoding, default is utf8.
}
readLines
Open the file and read a set of text lines in array mode. The end-of-line identifier is based on the setting of the EOL attribute. By default, posix: "\n"; windows: "\r\n"
1
2static Array fs.readLines(String fname,
Integer maxlines = -1);
Call parameters:
- fname: String, specify the file name
- maxlines: Integer, specifies the maximum number of lines to be read this time. By default, all text lines are read.
Return results:
- Array, returns an array of read text lines. If there is no data to read or the connection is interrupted, the array will be empty.
write
Write content to the file according to the file descriptor
1
2
3
4
5static Integer fs.write(FileHandle fd,
Buffer buffer,
Integer offset = 0,
Integer length = -1,
Integer position = -1) async;
Call parameters:
- fd:FileHandle, file descriptor object
- buffer:Buffer, to be writtenBufferobject
- offset: Integer,BufferData read offset, default is 0
- length: Integer, the number of bytes written to the file, the default is -1
- position: Integer, file writing location, default is the current file location
Return results:
- Integer, the actual number of bytes written
Write content to the file according to the file descriptor
1
2
3
4static Integer fs.write(FileHandle fd,
String string,
Integer position = -1,
String encoding = "utf8") async;
Call parameters:
- fd:FileHandle, file descriptor object
- string: String, the string to be written
- position: Integer, file writing location, default is the current file location
- encoding: String, specifies the decoding method, the default decoding is utf8
Return results:
- Integer, the actual number of bytes written
writeTextFile
Create a text file and write the content
1
2static fs.writeTextFile(String fname,
String txt) async;
Call parameters:
- fname: String, specify the file name
- txt: String, specifies the string to be written
writeFile
Create binary file and write content
1
2
3static fs.writeFile(String fname,
Buffer data,
String opt = "binary") async;
Call parameters:
- fname: String, specify the file name
- data:Buffer, specifies the binary data to be written
- opt: String, specifies write options, will be ignored
Create binary file and write content
1
2
3static fs.writeFile(String fname,
Buffer data,
Object options) async;
Call parameters:
- fname: String, specify the file name
- data:Buffer, specifies the binary data to be written
- options: Object, specifies write options, will be ignored
Create a file and write content
1
2
3static fs.writeFile(String fname,
String data,
String opt = "utf8") async;
Call parameters:
- fname: String, specify the file name
- data: String, specifies the data to be written
- opt: String, specify write options
Create a file and write content
1
2
3static fs.writeFile(String fname,
String data,
Object options) async;
Call parameters:
- fname: String, specify the file name
- data: String, specifies the data to be written
- options: Object, specify write options
The options supported by options are as follows:
1
2
3{
"encoding": "utf8" // specify the encoding, default is utf8.
}
appendFile
Create binary file and write content
1
2static fs.appendFile(String fname,
Buffer data) async;
Call parameters:
- fname: String, specify the file name
- data:Buffer, specifies the binary data to be written
setZipFS
set upzipvirtual file mapping
1
2static fs.setZipFS(String fname,
Buffer data);
Call parameters:
clearZipFS
Clearzipvirtual file mapping
1static fs.clearZipFS(String fname = "");
Call parameters:
- fname: String, specifies the mapping path, clears all caches by default
watch
Watch a file and return the corresponding watcher object
1static FSWatcher fs.watch(String fname);
Call parameters:
- fname: String, specifies the file object to be observed
Return results:
Watch a file and return the corresponding watcher object
1
2static FSWatcher fs.watch(String fname,
Function callback);
Call parameters:
- fname: String, specifies the file object to be observed
- callback: Function,
(evtType: 'change' | 'rename', filename: string) => any
the processing callback when the file object changes
Return results:
Watch a file and return the corresponding watcher object
1
2static FSWatcher fs.watch(String fname,
Object options);
Call parameters:
- fname: String, specifies the file object to be observed
- options: Object, observation options
Return results:
The options supported by options are as follows:
1
2
3
4
5{
"persistent": true, // specify whether the process should continue to run as long as files are being watched
"recursive": false, // specify whether all subdirectories should be watched or only the current directory
"encoding": "utf8", // specify the encoding, default is utf8.
}
Watch a file and return the corresponding watcher object
1
2
3static FSWatcher fs.watch(String fname,
Object options,
Function callback);
Call parameters:
- fname: String, specifies the file object to be observed
- options: Object, observation options
- callback: Function,
(evtType: 'change' | 'rename', filename: string) => any
the processing callback when the file object changes
Return results:
The options supported by options are as follows:
1
2
3
4
5{
"persistent": true, // specify whether the process should continue to run as long as files are being watched
"recursive": false, // specify whether all subdirectories should be watched or only the current directory
"encoding": "utf8", // specify the encoding, default is utf8.
}
watchFile
Observe a file and return the correspondingStatsWatcherobject
1
2static StatsWatcher fs.watchFile(String fname,
Function callback);
Call parameters:
- fname: String, specifies the file object to be observed
- callback: Function,
(curStats: Stats, prevStats: Stats) => any
the processing callback when the stats of the file object changes.
Return results:
- StatsWatcher,StatsWatcherobject
Observe a file and return the correspondingStatsWatcherobject
1
2
3static StatsWatcher fs.watchFile(String fname,
Object options,
Function callback);
Call parameters:
- fname: String, specifies the file object to be observed
- options: Object, observation options
- callback: Function,
(curStats: Stats, prevStats: Stats) => any
the processing callback when the stats of the file object changes.
Return results:
- StatsWatcher,StatsWatcherobject
The options supported by options are as follows:
1
2
3
4
5{
"persistent": true, // specify whether the process should continue to run as long as files are being watched
"recursive": false, // specify whether all subdirectories should be watched or only the current directory
"encoding": "utf8", // specify the encoding, default is utf8.
}
unwatchFile
From observing fname'sStatsWatcherRemove all observation event callbacks from
1static fs.unwatchFile(String fname);
Call parameters:
- fname: String, specifies the file object to be observed
Return results:
- StatsWatcherobject
From observing fname'sStatsWatchercallback
Remove the callback from the observation event callback
1
2static fs.unwatchFile(String fname,
Function callback);
Call parameters:
- fname: String, specifies the file object to be observed
- callback: Function, the callback to be removed
Return results:
- StatsWatcherobject
Even if the callback is no longerStatsWatcherNo error will be reported in the observation event callback
constant
SEEK_SET
seek method constant, move to absolute position
1const fs.SEEK_SET = 0;
SEEK_CUR
seek method constant, move to the relative position of the current position
1const fs.SEEK_CUR = 1;
SEEK_END
seek mode constant, move to the relative position of the end of the file
1const fs.SEEK_END = 2;