Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Readable Stream #3424

Closed
coodin opened this issue Jun 23, 2021 · 2 comments
Closed

Custom Readable Stream #3424

coodin opened this issue Jun 23, 2021 · 2 comments

Comments

@coodin
Copy link

coodin commented Jun 23, 2021

  • 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.
-->

@Ayase-252
Copy link
Member

Ayase-252 commented Jun 24, 2021

_construct (nodejs/node#29656) was added in Node.js v15.0. You need use v15.0 and above (ideally, v16).

@coodin
Copy link
Author

coodin commented Jun 24, 2021

Yea I think , it was the problem because it is worked when I upgradated latest version of nodejs.

@coodin coodin closed this as completed Jun 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants