Skip to content

Custom Readable Stream #3424

Closed
Closed
@coodin

Description

@coodin
  • v14.17.0:
  • Windows:
  • Scope (install, code, runtime, meta, other?):
  • Module (and version) (if relevant):
const { Readable } = require('stream');
const fs = require('fs');


class ReadStream extends Readable {
  constructor(filename) {
    super();
    this.filename = filename;
    this.fd = null;
  }
  _construct(callback) {
    fs.open(this.filename, (err, fd) => {
      if (err) {
        callback(err);
      } else {
        this.fd = fd;
        consolelog("fd:", this.fd);
        callback();
      }
    });
  }
  _read(n) {
    const buf = Buffer.alloc(n);
    fs.read(this.fd, buf, 0, n, null, (err, bytesRead) => {
      if (err) {
        this.destroy(err);
      } else {
        this.push(bytesRead > 0 ? buf.slice(0, bytesRead) : null);
      }
    });
  }
  _destroy(err, callback) {
    if (this.fd) {
      fs.close(this.fd, (er) => callback(er || err));
    } else {
      callback(err);
    }
  }
}

const example = new ReadStream("./lol.txt");
example.on("data", (chunk) => {
  console.log(chunk);
})

The error I have is that TypeError [ERR_INVALID_ARG_TYPE]: The "fd" argument must be of type number. Received null from fs.read() inside _read method because it has not been encountered _construct method before _read method which it should have encountered depend on documentation. I am not sure I am right but thank you for contribution already.
-->

Metadata

Metadata

Assignees

No one assigned

    Labels

    answered🎉 Yay! The issue has been resolved, or the question has been answered.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions