17

I m currently trying to read some files with fs module for node.js. Since it lack a tot of the function I m used to (fseek(), getline()...), I m creating another module to get them back. (a node.js copy of C stdio.h).

My simple question is:

Does seek() exist in some other name or do I need to remplement almost every function to have it?

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
  • Note to anyone still seeing this question: This was not the right way to go about it, and the `fs` library have evolved to expose methods like `readFile` that are _way_ more effective to answering my problem – DrakaSAN Jul 19 '21 at 08:32

2 Answers2

23

In node.js the seek functionality is included in the read function. When you use the fs.read function, there is a parameter called position, that works as the seek position.

If what you want is to write to the file, the function fs.write also has the position parameter.

Check the docs here: https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • 3
    Note: "If position is an integer, the file position will remain unchanged.". When you pass in a position and read some bytes, the file position doesn't get moved by the read amount. The only way to continue reading incrementally is to keep track of position + bytes read and keep reading from the new position. – Ates Goral May 22 '20 at 02:41
  • 3
    ok, what about `SEEK_END`? – sherpya Oct 04 '22 at 02:17
3

This package is worth looking at: https://npmjs.org/package/fs-ext

Besides the package, Closest I could find would be : http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options or using these parameters on 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.
CBIII
  • 845
  • 1
  • 9
  • 9
  • 1
    NodeJS v6.5.0 no longer has the `length` property; it has been replaced by the `start` and `end` properties, which determine **from** and **to** which line the file should be read, respectively. I included an example in my answer [here](http://stackoverflow.com/a/39391650/2929693). – D. Visser Sep 08 '16 at 13:02