在 Node.js 中使用文件描述符
Before you're able to interact with a file that sits in your filesystem, you must get a file descriptor.
A file descriptor is a reference to an open file, a number (fd) returned by opening the file using the open()
method offered by the fs
module. This number (fd
) uniquely identifies an open file in operating system:
JS
Notice the r
we used as the second parameter to the fs.open()
call.
That flag means we open the file for reading.
Other flags you'll commonly use are:
Flag | Description | File gets created if it doesn't exist |
---|---|---|
r+ | This flag opens the file for reading and writing | ❌ |
w+ | This flag opens the file for reading and writing and it also positions the stream at the beginning of the file | ✅ |
a | This flag opens the file for writing and it also positions the stream at the end of the file | ✅ |
a+ | This flag opens the file for reading and writing and it also positions the stream at the end of the file | ✅ |
You can also open the file by using the fs.openSync
method, which returns the file descriptor, instead of providing it in a callback:
JS
Once you get the file descriptor, in whatever way you choose, you can perform all the operations that require it, like calling fs.close()
and many other operations that interact with the filesystem.
You can also open the file by using the promise-based fsPromises.open
method offered by the fs/promises
module.
The fs/promises
module is available starting only from Node.js v14. Before v14, after v10, you can use require('fs').promises
instead. Before v10, after v8, you can use util.promisify
to convert fs
methods into promise-based methods.
JS
Here is an example of util.promisify
:
JS
To see more details about the fs/promises
module, please check fs/promises API.