0

I'm trying to read the first 100 bytes of a file named example.txt using fs.read in this Node.JS code:

"use strict";

const fs = require("fs");

fs.open("example.txt", function(err, fd) {
    if(err) {
        console.error(err);
    } else {
        fs.read(fd, Buffer.alloc(100), function onFileRead(err, bytesRead, buffer) {
            if(err) {
                console.error(err);
            } else if(bytesRead >= buffer.byteLength) {
                console.log("BEHOLD:\n" + buffer.toString());
            } else {
                console.log(`Read progress: ${ bytesRead } bytes (${ bytesRead / buffer.length * 100 }%)`);
            }
        });
    }
});

But running the code generates this error:

TypeError [ERR_INVALID_ARG_TYPE]: The "buffer" argument must be an instance of Buffer, TypedArray, or DataView. Received an instance of ArrayBuffer
←[90m    at Object.read (fs.js:492:3)←[39m
    at C:\Users\...\bufferTest.js:9:12
←[90m    at FSReqCallback.oncomplete (fs.js:155:23)←[39m {
  code: ←[32m'ERR_INVALID_ARG_TYPE'←[39m
}

This error makes no sense to me. How can a buffer returned by Buffer.alloc not be an instance of Buffer? Replacing Buffer.alloc(100) with Buffer.alloc(100).buffer or new Uint8Array(100) doesn't fix the issue either. I'm currently using Node.JS version 14.17.6 (LTS).

1 Answer 1

1

The Syntax is : fs.read(fd, [options,] callback) options : is an object, it has a property buffer which has a default value of Buffer.alloc(16384)

fs.open("example.txt", function(err, fd) {

if (err) {

    console.error(err);

} else {

    let readBuffer = Buffer.alloc(100);

   // See here  buffer is the name of a property in the options object which is passed to the read method in fs

    fs.read(fd, {
        buffer: readBuffer
    }, function onFileRead(err, bytesRead, buffer) {

        if (err) {

            console.error(err);

        } else if (bytesRead >= buffer.byteLength) {

            console.log("BEHOLD:\n" + buffer.toString());

        } else {

            console.log(`Read progress: ${ bytesRead } bytes (${ bytesRead / buffer.length * 100 }%)`);

        }

    });

}

});

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

1 Comment

Read the documentation on nodejs.org, It works if all the parameters for the read function are explicitly mentioned like this : fs.read(fd,buffer,0,buffer.length,null, function onFileRead(err, bytesRead, buffer) { if(err) { console.error(err); } else if(bytesRead >= buffer.byteLength) { console.log("BEHOLD:\n" + buffer.toString()); } else { console.log(Read progress: ${ bytesRead } bytes (${ bytesRead / buffer.length * 100 }%)); } });

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.