May 10, 2021 Node.js
Node .js documentation provides a detailed .js of Node's file system.
稳定性: 3 - 稳定
The node .js file system module is a collection that encapsulates standard POSIX file I/O operations.
Use
require('fs')
where all methods are synchronized and asynchronous.
The last argument of an asynchronous method is a callback function, and the parameters of this callback depend on the method, although the first argument is generally an exception.
If the operation is successful, the first argument
null
undefined
When using a synchronization operation, any exception is thrown immediately, and the exception can be handled with try/catch to make the program work properly.
Here is an example of an asynchronous operation:
var fs = require('fs');
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
Here's an example of a synchronization operation:
var fs = require('fs');
fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
Asynchronous methods do not guarantee the order of operations, so the following example is prone to errors:
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
The reason for the error in this example is probably that the
fs.stat
and the correct method is as follows:
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
});
});
Asynchronous methods are highly recommended in busy processes. The synchronization method blocks the entire process until the method is complete.
A relative path may be used, which is
process.cwd()
Most fs functions ignore callback parameters and, if ignored, throw exceptions with the default function. If you want stack information for the original call point, you need to set the environment NODE_DEBUG:
$ cat script.js
function bad() {
require('fs').readFile('/');
}
bad();
$ env NODE_DEBUG=fs node script.js
fs.js:66
throw err;
^
Error: EISDIR, read
at rethrow (fs.js:61:21)
at maybeCallback (fs.js:79:42)
at Object.fs.readFile (fs.js:153:18)
at bad (/path/to/script.js:2:17)
at Object.<anonymous> (/path/to/script.js:5:1)
<etc.>
Asynchronous function reame (2). T he callback function has only one argument: a possible exception.
The synchronization function reame (2).
Return
undefined
The asynchronous function ftruncate (2). The callback function has only one argument: a possible exception.
The synchronization function ftruncate (2).
Return
undefined
The asynchronous function truncate (2). T
he callback function has only one argument: a possible exception.
The file descriptor can also be used as the first argument, and in
fs.ftruncate()
The synchronization function truncate (2).
Return
undefined
The asynchronous function chown (2). The callback function has only one argument: a possible exception.
The synchronization function chown (2).
Return
undefined
Asynchronous function fchown (2). The callback function has only one argument: a possible exception.
The synchronization function fchown (2).
Return
undefined
Asynchronous function lchown (2). The callback function has only one argument: a possible exception.
The synchronization function lchown (2).
Return
undefined
Asynchronous function chmod (2). The callback function has only one argument: a possible exception.
The synchronization function chmod (2).
Return
undefined
Asynchronous function fchmod (2). The callback function has only one argument: a possible exception.
The synchronization function fchmod (2).
Return
undefined
Asynchronous function lchmod (2). The callback function has only one argument: a possible exception.
Available only on Mac OS X.
The synchronization function lchmod (2).
Return
undefined
The asynchronous function stat (2). T
he callback function has two parameters: (err, stats),
stats
is
fs.Stats
object. F
or more information, please refer to fs. S
tats。
The asynchronous function lstat (2). T
he callback function has two parameters: (err, stats),
stats
is
fs.Stats
object.
lstat()
stat()
difference being that if path is
path
link, it reads the link itself, not the file to which it is linked.
The asynchronous function fstat (2). T
he callback function has two parameters: (err, stats), where
stats
is an
fs.Stats
object.
The synchronization function stat (2). R
eturn
fs.Stats
instance.
The synchronization function lstat (2). R
eturn
fs.Stats
instance.
The synchronization function fstat (2). R
eturn
fs.Stats
instance.
Asynchronous function link (2). The callback function has only one argument: a possible exception.
Sync function link (2).
Return
undefined
Asynchronous function symlink (2). The callback function has only one argument: a possible exception.
type
may
'dir'
'file'
'junction'
(the default
'file'
and is only valid in Windows (other systems are not considered). N
ote that Windows Junction requires the destination address to be absolute.
When
'junction'
the
destination
automatically converted to an absolute path.
Sync function symlink (2).
Return
undefined
Asynchronous function readlink (2).
The callback function has 2
(err, linkString)
.
The synchronization function readlink (2). Returns the string value of the symbolic link.
The asynchronous function realpath (2). T
he callback function has 2
(err,resolvedPath)
You
process.cwd
to solve the relative path problem.
For example:
var cache = {'/etc':'/private/etc'};
fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
if (err) throw err;
console.log(resolvedPath);
});
The synchronization function realpath (2). Returns the resolved path.
Asynchronous function unlink (2). The callback function has only one argument: a possible exception.
The synchronization function unlink (2).
Return
undefined
Asynchronous function rmdir (2). The callback function has only one argument: a possible exception.
The synchronization function rmdir (2).
Return
undefined
Asynchronous function mkdir (2). T
he callback function has only one argument: a possible exception.
mode
defaults
0777
.
The synchronization function mkdir (2).
Return
undefined
The asynchronous function readdir (3). R
ead the contents of the folder. T
he callback has 2
(err, files)
are in the folder except the name '.' a
nd '.'.
All file names other than .
The synchronization function readdir (3). R
eturns in addition to the
'.'
a
nd
'..'
All the files except.
Asynchronous function close (2). The callback function has only one argument: a possible exception.
The synchronization function close (2).
Return
undefined
Asynchronous function file open. S
ee open (2).
flags
are:
'r'
- Opens in read-only mode and throws an exception if the file does not exist.
'r+'
- opens in read-write mode and throws an exception if the file does not exist.
'rs'
- Synchronized, open in read-only mode; T
his feature is primarily used to open NFS-mounted files because it allows you to skip potentially outdated local caches.
Do not use this flag bit if you care about I/O performance.
This is not the
fs.open()
a synchronous blocking request, and if you
fs.openSync()
'rs+'
- Open the file as read and write in sync mode.
See
'rs'
.
'w'
- Opens in write-only mode.
The file is either created (if the file does not exist) or overwritten (if present).
'wx'
- similar
'w'
if the file storage operation fails
'w+'
- Opens as readable and writeable. T
he file is created (if the file does not exist) or overwritten (if present)
'wx+'
- similar to
'w+'
if the file storage operation fails.
'a'
- Opens in an additional form.
If the file does not exist, create one.
'ax'
- similar
'a'
if the file storage operation fails.
'a+'
the file as read-only and attached.
If the file does not exist, it is established
'ax+'
and
'a+'
similar if the file storage operation fails.
If the file exists,
mode
sets the file mode (permission and sticky bits).
The default
0666
readable and written.
The callback has 2
(err, fd)
.
Excluding the
'x'
(the O_EXCL for open(2)) guarantees
path
is newly created.
O_EXCL
I
n POSIX systems, files are considered to exist even if they do not exist.
Exclusion tags do not determine whether they are valid in the network file system.
In Linux systems, files opened in append mode cannot be written in a specified location. The core of the system ignores the location parameters and writes the data to the end of the file each time.
fs.open()
Returns a file descriptor in integer form.
Change the timestamp of the specified path file.
fs.utimes()
Return
undefined
Change the timestamp that the incoming file descriptor points to the file.
fs.futimes()
Return
undefined
Asynchronous function fsync (2). The callback function has only one argument: a possible exception.
Synchronize fsync (2).
Return
undefined
Write
buffer
to the file specified by
fd
The
offset
length
determine which part of the cache is written.
The argument
position
the location of the file to be written to. I
f
typeof position !== 'number'
be written at the current location.
See pwrite (2).
The callback function has three
(err, written, buffer)
written
of the
buffer
are used to write.
Note that if
fs.write
has not been executed,
fs.write
which is not safe.
Therefore,
fs.createWriteStream
In Linux systems, files opened in append mode cannot be written in a specified location. The core of the system ignores the location parameters and writes the data to the end of the file each time.
Write
buffer
to the file specified by
fd
If
data
not a buffer, it is cast to a string.
The argument
position
the location of the file to be written to. I
f
typeof position !== 'number'
be written at the current location.
See pwrite (2).
Argument
encoding
How strings are encoded.
The callback function has three
(err, written, buffer)
written
of the
buffer
are used to write. N
ote that the bytes written are different from the string characters.
See
Buffer.byteLength.
Between writing
buffer
the entire string must be written and not intercepted.
This is because the displacement of the returned byte is different from the displacement of the string.
Note that if
fs.write
has not been executed,
fs.write
which is not safe.
Therefore,
fs.createWriteStream
In Linux systems, files opened in append mode cannot be written in a specified location. The core of the system ignores the location parameters and writes the data to the end of the file each time.
fs.write()
Returns the number of bytes to write.
Read
fd
specified file.
buffer
a buffer and the data will be written here.
offset
write offset
length
the file that length needs to read
position
reads the starting position of the
position
null
it will be read from the current location.
The callback function has 3
(err, bytesRead, buffer)
.
fs.read
Returns
bytesRead
filename
{String}
options
{Object}
encoding
{String |
Null's default is
null
flag
(String) default s
'r'
callback
{Function}
Read the contents of the entire file asynchronously. For example:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
The callback function has 2
(err, data)
are the
data
of the file.
If the parameter
encoding
specified, the native buffer is returned
fs.readFile
Returns the contents of the entire file.
If the parameter
encoding
specified, a buffer is returned.
filename
{String}
data
{String |
Buffer}
options
{Object}
encoding
{String |
Null's default is
'utf8'
mode
{Number} Default =
438
(aka
0666
in Octal)
flag
{String} Default =
'w'
callback
{Function}
Write the file asynchronously and replace it if it already exists.
data
can be a cache or a string.
If the
data
is buffer, the parameter
encoding
The default is
'utf8'
Columns such as:
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
fs.writeFile
Return
undefined
filename
{String}
data
{String |
Buffer}
options
{Object}
encoding
{String |
Null's default is
'utf8'
mode
(Number) Default s
438
(aka
0666
in Octal)
flag
are the default of
'a'
callback
{Function}
Add data to the file asynchronously and create one if the file does not exist.
data
can be a cache or a string.
For example:
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
fs.appendFile
Return
undefined
稳定性: 2 - 不稳定。 尽可能的用 fs.watch 来替换。
Monitor
filename
files.
Listener is called whenever a file is
listener
The second argument is optional. I
f so, it must contain objects with two
persistent
interval
and interval).
persistent
whether the process continues to run when the file is monitored.
interval
specifies the interval, in milliseconds, between query files.
The default value is .persistent: true, interval: 5007.
Listener has two parameters, the first for the current state of the file and the second for the previous state of the file:
fs.watchFile('message.text', function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});
The file state object type in listener is fs. Stat。
If you want to be notified when you modify a file, rather than when you access
curr.mtime
prev.mtime
稳定性: 2 - 不稳定. 尽可能的用 fs.watch 来替换。
Stop monitoring
filename
files. I
f a
listener
it will only be
listener
Otherwise, remove all listener and stop monitoring
filename
Calling
fs.unwatchFile()
monitoring an unsnoted file, does not trigger an error, but a no-op occurs.
稳定性: 2 - 不稳定.
Observe changes to files or folders specified by
filename
T
he return object
is fs.
FSWatcher
。
The second argument is optional. I
f so, it must be an object that contains two
persistent
recursive
persistent
whether the process continues to run when the file is monitored.
recursive
whether to monitor all sub-folders or current folders, a parameter that is valid only if the monitoring object is a folder and only in supported systems (see notes below).
The default
{ persistent: true, recursive: false }
.
The callback function has 2
(event, filename)
event
is
rename
or
change
filename
file name that triggered the event.
fs.watch
APIs are not 100% cross-platform compatible and may not be available in some cases.
recursive
parameter is only available on OS X.
FSEvents
monitoring of this type of file, so it is unlikely that new platforms will be added in the future.
These features rely on the underlying system to provide notification of file system changes.
inotify
.
kqueue
.
kqueue
folders use
FSEvents
.
event ports
.
ReadDirectoryChangesW
.
If the underlying system function is
fs.watch
does not work. F
or example, monitoring network file systems (NFS, SMBs, etc.) is often not useful. Y
ou can still query
fs.watchFile
but it's slow and unreliable.
Callback functions provide file name parameters that are not available on every platform (not for Linux and Windows). E
ven on available platforms, there is no guarantee that they will be available.
So don't assume that the
filename
callback function is valid, add some empty logical judgment to your code.
fs.watch('somedir', function (event, filename) {
console.log('event is: ' + event);
if (filename) {
console.log('filename provided: ' + filename);
} else {
console.log('filename not provided');
}
});
To determine the existence of a file, the callback function argument is the bool value. For example:
fs.exists('/etc/passwd', function (exists) {
util.debug(exists ? "it's there" : "no passwd!");
});
fs.exists()
an older version of the function, so don't use it in code.
In addition, to determine if there is a vulnerability before opening the file, another process may have removed the file between the
fs.exists()
and
fs.open()
calls.
It is best
fs.open()
to determine if there is an error based on the callback function.
fs.exists()
removed in the future.
fs.exists()
If the file exists to
true
otherwise false is
false
fs.existsSync()
in the future.
Test the user rights of
path
that the parameter path points to. T
he optional parameter
mode
an integer, which represents the permissions that need to be checked. A
ll values are listed below.
mode
can be a single value, or multiple permission checks can be performed by or through a mask operation.
fs.F_OK
- The file is visible to the process and can be used to check for the existence of the file. T
he
mode
for the argument mode.
fs.R_OK
Whether the file is readable to the process.
fs.W_OK
Whether the file is writeable to the process.
fs.X_OK
- Whether the file is executable for the process. (
Windows system is not available, the execution effect is equivalent
fs.F_OK
)
The third argument is the callback function. I
f the check fails, the argument to the callback function is an error in the response.
The following example checks whether
/etc/passwd
can be read and written by the current process.
fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function(err) {
util.debug(err ? 'no access!' : 'can read/write');
});
fs.access
I
f an error is thrown, nothing is done.
fs.stat()
fs.lstat()
and
fs.fstat()
as the returned objects of the synchronized version.
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with
fs.lstat()
)
stats.isFIFO()
stats.isSocket()
Using
util.inspect(stats)
a string similar to the following:
{ dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
atime
mtime
birthtime
ctime are
ctime
of Date
and need to be compared in the appropriate way.
used
to get the timestamp
(milliseconds, starting at 1 January 1970 00:00:00 UTC),
which basically meets any comparison criteria. T
here are other ways to display additional information.
See
MDN JavaScript Reference for more
State objects have the following semantics:
atime
Time - The last time the file was accessed.
mknod(2)
utimes(2)
read(2)
can be changed.
mtime
time - the last time the file was modified.
mknod(2)
utimes(2)
write(2)
can be changed.
ctime
change time - the last modification time of the file state (inode).
chmod(2)
chown(2)
link(2)
mknod(2)
rename(2)
unlink(2)
utimes(2)
read(2)
write(2)
can be changed.
birthtime
"Birth Time" - File creation time, file creation time. I
n some file systems that do not provide file lifetime, this field is populated with ctime or 1970-01-01T00:00Z (ie, unix epoch timestamp 0).
In Darwin and other FreeBSD system variants, atime is also explicitly set to a time value earlier than its current firsttime, a process that uses utimes(2) system calls.
Prior to the version of Node v0.12, there was a time value for ctime in Windows systems. Note that in v.0.12, ctime is no longer "creation time", and in Unix systems, he has not.
Returns a readable stream object
Readable Stream
options
default is as follows:
{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
autoClose: true
}
The
options
the
start
and
end
to read a specific range of contents of the file, not the entire file.
start
and
end
both in the file range and start at 0,
encoding
'utf8'
'ascii'
'base64'
If you
fd
value,
ReadStream
ignores
path
parameter and uses the file description so that no open event
open
If
autoClose
false, files won't close even if an error occurs, and you'll be responsible for closing them to avoid file descriptors being leaked. I
f
autoClose
true (the default), the file descriptor is
end
off when you encounter error or end.
error
For example, from a 100-byte file, read at least 10 bytes:
fs.createReadStream('sample.txt', {start: 90, end: 99});
ReadStream
is
Readable Stream.
fd
used by fd .
Triggered when you create ReadStream for a file.
Return a new write object
Writable Stream
options
is an object, the default:
{ flags: 'w',
encoding: null,
fd: null,
mode: 0666 }
Options can also include a start option to write data to the start of the specified file. Modifying without replacing the file requires the flags pattern to be specified as r-plus rather than a silent w.
Similar to
ReadStream
fd
empty,
WriteStream
path
and instead uses the file description so that no open event is
open
WriteStream
is
Writable Stream.
fd
used by fd
Triggered when the WhiteStream file is opened.
The number of bytes currently written, excluding data waiting to be written.
fs.watch()
is this class.
Stop
fs.FSWatcher
object.
event
type of event that has changed
filename
(String) Changed File Name (if relevant/available)
When a listening file or folder changes, see fs.watch.
error
{Error object}
Triggered when an error occurs.