1

Can you have Node.js read a file as binary into a specific slot of memory somehow?

let buffer = new Uint8Array
let location = 0
let path = 'foo.binary'
fs.readIntoMemoryLocation(path, buffer, location)

Is something like that possible?

I am wondering because I have a bunch of stuff to process in one array buffer, and would like to add a file to it, rather than the file being its own buffer. Without copying the file from one place to another either. If not in Node.js, then the browser somehow?

1 Answer 1

2

Can you have Node.js read a file as binary into a specific slot of memory somehow?

Yes, both the fileHandle.read() and the fs.read() interfaces allow you to pass in a buffer and offset into that buffer that you want it to read data into.

The fs.readFile() interface does not provide that so you will have to open the file yourself and read the data yourself into the buffer and then close the file. If you stat the file to see how big it is, you can still read the whole file into the buffer with one read operation.

Sign up to request clarification or add additional context in comments.

2 Comments

Horray, thank you!!! Is there some way to do this in the browser too? :D
@LancePollard it should be possible in a browser through the .stream() method, which would allow you to read that streams data into your own ArrayBufferView (hence allowing to write in a single ArrayBuffer that you could assign beforehand), except that no vendor has implemented ReadableStreamBYOBReader yet... so the second closest you'll get is to use a ReadableStreamDefaultReader and to have one small ArrayBuffer assigned for every chunk, and to copy this chunk's data into your final big ArrayBuffer, a lot less efficient...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.