Reputation: 43
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).
Upvotes: 0
Views: 1173
Reputation: 61
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 }%)`);
}
});
}
});
Upvotes: 1