I am trying to use the fs/promises
module. Node version is v14.17.0
The code below throws an error: TypeError: read is not a function
(async () => {
'use strict';
const { open, read } = require('fs/promises');
const fd = await open('/proc/loadavg', 'r');
const { bytesRead, buffer } = await read(fd, Buffer.alloc(1024));
console.log({ bytesRead, data: buffer.toString() });
})()
.catch(console.error);
When I try it with the non promise version it works.
'use strict';
const { open, read } = require('fs');
const { exit } = require('process');
open('/proc/loadavg', 'r', (err, fd) => {
if (err) {
console.error(err);
exit(2);
}
read(fd, Buffer.alloc(1024), 0, 1024, 0, (err, bytesRead, buffer) => {
if (err) {
console.error(err);
exit(2);
}
console.log({ bytesRead, data: buffer.toString() });
});
});
Why is the first one not working?
Edit: Here is what vscode is showing me. According to one comment this isn’t true.
I found the type in fs.d.ts
function read<TBuffer extends Uint8Array>(
handle: FileHandle,
buffer: TBuffer,
offset?: number | null,
length?: number | null,
position?: number | null,
): Promise<{ bytesRead: number, buffer: TBuffer }>;
Reading in the promise interface is done via fileHandle.read()
, not via fs.promises.read()
.
You could manually promisify fs.read()
and fs.open()
yourself, but the intention of the promise interface is to direct people to use the fileHandle interface instead which has some advantages.
Also, this code:
const fd = await open('/proc/loadavg', 'r');
doesn’t return an fd
. It returns a fileHandle object (which you then do .read()
on, so you’ll have to change the .read()
code and the .close()
code for that anyway.