7

Is it possible to create a stream that reads from a specific position of file in node.js?

I know that I could use a more traditional fs.open / seek / read API, but in that case I need to somehow wrap them in a stream for underlying layers of my application.

vdudouyt
  • 843
  • 7
  • 14

1 Answers1

14

fs.createReadStream() has an option you can pass it to specify the start position for the stream.

let f = fs.createReadStream("myfile.txt", {start: 1000});

You could also open a normal file descriptor with fs.open(), then fs.read() one byte from a position right before where you want the stream to be positioned using the position argument to fs.read() and then you can pass that file descriptor into fs.createReadStream() as an option and the stream will start with that file descriptor and position (though obviously the start option to fs.createReadStream() is a bit simpler).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Theoretically I can use that to stream a audio file starting from a specific position, right? – florianmaxim Feb 18 '17 at 00:20
  • 1
    @cheesyeyes - That depends. If you're looking for an [audio-streaming protocol](http://www.garymcgath.com/streamingprotocols.html), a node.js stream is not that all by itself. If you're looking to just deliver a certain set of bytes from a file, then a node.js stream could do that. – jfriend00 Feb 18 '17 at 04:07