writable._construct(callback)


  • callback <Function> 当流初始化完成后调用此函数(可选择传入一个错误参数)。

_construct() 方法不能被直接调用。它可以由子类实现,如果实现了,也只会被内部的 Writable 类方法调用。

【The _construct() method MUST NOT be called directly. It may be implemented by child classes, and if so, will be called by the internal Writable class methods only.】

在流构造函数返回之后,这个可选函数将在一个时间片中被调用,从而延迟任何 _write()_final()_destroy() 的调用,直到调用 callback。这对于在流可用之前初始化状态或异步初始化资源非常有用。

【This optional function will be called in a tick after the stream constructor has returned, delaying any _write(), _final() and _destroy() calls until callback is called. This is useful to initialize state or asynchronously initialize resources before the stream can be used.】

const { Writable } = require('node:stream');
const fs = require('node:fs');

class WriteStream extends Writable {
  constructor(filename) {
    super();
    this.filename = filename;
    this.fd = null;
  }
  _construct(callback) {
    fs.open(this.filename, 'w', (err, fd) => {
      if (err) {
        callback(err);
      } else {
        this.fd = fd;
        callback();
      }
    });
  }
  _write(chunk, encoding, callback) {
    fs.write(this.fd, chunk, callback);
  }
  _destroy(err, callback) {
    if (this.fd) {
      fs.close(this.fd, (er) => callback(er || err));
    } else {
      callback(err);
    }
  }
}