文件描述符和i node_在Node中使用文件描述符

文件描述符和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 writing

    r+打开文件进行读写

  • w+ open the file for reading and writing, positioning the stream at the beginning of the file. The file is created if not existing

    w+打开文件进行读写,将流放在文件的开头。 如果不存在则创建文件

  • a open the file for writing, positioning the stream at the end of the file. The file is created if not existing

    a打开文件进行写入,在文件的结尾流定位。 如果不存在则创建文件

  • a+ open the file for reading and writing, positioning the stream at the end of the file. The file is created if not existing

    a+打开文件进行读写,将流放在文件末尾。 如果不存在则创建文件

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()以及与文件系统交互的许多其他操作。

翻译自: https://flaviocopes.com/node-file-descriptors/

文件描述符和i node

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值