【问题标题】:seek() equivalent in javascript/node.js?javascript/node.js 中的 seek() 等价物?
【发布时间】:2013-07-25 10:17:06
【问题描述】:

我目前正在尝试使用 node.js 的 fs 模块读取一些文件。 由于它缺少我习惯使用的大部分功能(fseek(),getline()...),我正在创建另一个模块来取回它们。 (C stdio.h 的 node.js 副本)。

我的简单问题是:

seek() 是否以其他名称存在,或者我需要重新实现几乎每个函数才能拥有它?

【问题讨论】:

  • 对仍然看到这个问题的人请注意:这不是解决问题的正确方法,fs 库已经发展为公开像 readFile 这样的方法 way i> 更有效地回答我的问题

标签: javascript node.js file-io


【解决方案1】:

在 node.js 中,seek 功能包含在 read 函数中。使用fs.read函数时,有一个叫position的参数,作为seek位置。

如果你想要写入文件,函数fs.write也有position参数。

在此处查看文档: https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback

【讨论】:

  • 注意:“如果位置是整数,文件位置将保持不变。”。当您传入一个位置并读取一些字节时,文件位置不会被读取量移动。继续增量读取的唯一方法是跟踪读取的位置 + 字节数并继续从新位置读取。
【解决方案2】:

这个包值得一看: https://npmjs.org/package/fs-ext

除了包裹,我能找到的最近的是: http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options 或在 fs.read 上使用这些参数

length is an integer specifying the number of bytes to read.

position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

【讨论】:

  • NodeJS v6.5.0 不再具有length 属性;它已被startend 属性替换,它们分别确定fromto 应该读取文件的哪一行。我在回答 here 中包含了一个示例。
猜你喜欢
  • 2013-01-06
  • 1970-01-01
  • 2016-01-19
  • 2014-02-27
  • 2013-08-25
  • 1970-01-01
  • 2013-10-08
  • 2014-01-08
  • 1970-01-01
相关资源
最近更新 更多