文件描述符和i node
Before you’re able to interact with a file that sits in your filesystem, you must get a file descriptor.
在与位于文件系统中的文件进行交互之前,必须获取文件描述符。
A file descriptor is what’s returned by opening the file using the open()
method offered by the fs
module:
文件描述符是使用fs
模块提供的open()
方法open()
文件后返回的内容:
const fs = require('fs')
fs.open('/Users/flavio/test.txt', 'r', (err, fd) => {
//fd is our file descriptor
})
Notice the r
we used as the second parameter to the fs.open()
call.
注意,我们将r
用作fs.open()
调用的第二个参数。
That flag means we open the file for reading.
该标志意味着我们打开文件进行读取。
Other flags you’ll commonly use are
您通常会使用的其他标志是
r+
open the file for reading and writingr+
打开文件进行读写w+
open the file for reading and writing, positioning the stream at the beginning of the file. The file is created if not existingw+
打开文件进行读写,将流放在文件的开头。 如果不存在则创建文件a
open the file for writing, positioning the stream at the end of the file. The file is created if not existinga
打开文件进行写入,在文件的结尾流定位。 如果不存在则创建文件a+
open the file for reading and writing, positioning the stream at the end of the file. The file is created if not existinga+
打开文件进行读写,将流放在文件末尾。 如果不存在则创建文件
You can also open the file by using the fs.openSync
method, which instead of providing the file descriptor object in a callback, it returns it:
您也可以使用fs.openSync
方法打开文件,该方法不会在回调中提供文件描述符对象,而是返回它:
const fs = require('fs')
try {
const fd = fs.openSync('/Users/flavio/test.txt', 'r')
} catch (err) {
console.error(err)
}
Once you get the file descriptor, in whatever way you choose, you can perform all the operations that require it, like calling fs.open()
and many other operations that interact with the filesystem.
一旦获得了文件描述符,就可以通过任何选择的方式执行所有需要它的操作,例如调用fs.open()
以及与文件系统交互的许多其他操作。
文件描述符和i node