fs.createReadStream() at specific position of file
Asked Answered
S

1

8

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.

Soever answered 14/11, 2016 at 1:43 Comment(0)
V
15

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).

Vanadium answered 14/11, 2016 at 2:2 Comment(2)
Theoretically I can use that to stream a audio file starting from a specific position, right?Beautician
@cheesyeyes - That depends. If you're looking for an audio-streaming protocol, 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.Vanadium

© 2022 - 2024 — McMap. All rights reserved.