网站搜索

javascript - 如何在 Node.js 中创建带有事件和管道的函数


我正在用 TypeScript 编写一个 Node.js 库,这个库的主要功能是从给定的 URL 下载内容,我希望它的使用方式如下

import library from 'library'

library('https://www.example.com')
    .on('progress', (progress: progress) => {
        //do something with the progress
    })
    .on('end', () => {
        //do something when done
    })
    .pipe(fs.createWriteStream('./test/file.mp4'))

我从来没有以这样的方式处理过 Node 事件和流,所以我完全不知道该如何着手,我也在使用 TypeScript 和 Webpack,请原谅我的英语不好

答案#1

你将需要实现一个可读流。Node 流是 EventEmitter 的实例,所以你可以自动使用事件 API。

至少,你需要实现一个 _read() 方法,当消费者准备好从队列中接收更多数据时,这个方法会被内部调用。由于你希望库能够报告进度,你还需要跟踪已处理的数据量,并相应地触发事件。

下面的代码忽略了几个重要的东西,比如背压,但这是一个开始。我正在使用 node-fetch 作为请求库,因为它暴露了底层的响应流,并且相当容易使用。

// fileLoader.js
const {Readable} = require('stream')
const fetch = require('node-fetch')

class FileLoader extends Readable {
  constructor(url) {
    super()
    this._url = url
    this._fetchStarted = false
    this._totalLength = 0
    this._currentLength = 0
  }

  _processData(stream) {
    stream
      .on('end', () => {
        this.push(null)
      })
      .on('error', (err) => {
        this.destroy(err)
      })
      .on('data', (chunk) => {
        this._currentLength += chunk.length
        if (this._totalLength) {
          this.emit('progress', Math.round(this._currentLength / this._totalLength * 100))
        }
        this.push(chunk)
      })
  }

  _startFetch() {
    fetch(this._url)
      .then((res) => {
        if (!res.ok) {
          return this.destroy(new Error(`fetch resulted in ${res.status}`))
        }
        this._totalLength = res.headers.get('content-length')
        this._processData(res.body)
      })
      .catch((err) => {
        return this.destroy(new Error(err))
      })
  }

  _read() {
    if (!this._fetchStarted) {
      this._fetchStarted = true
      this._startFetch()
    }
  }
}

module.exports.loadFile = (url) => new FileLoader(url)

以及消费者代码:

// consumer.js
const fs = require('fs')
const {loadFile} = require('./fileLoader')

loadFile('http://example.com/video.mp4')
  .on('progress', (progress) => {
    console.log(`${progress}%`)
  })
  .on('end', () => {
    console.log('done')
  })
  .on('error', (err) => {
    console.log(err)
  })
  .pipe(fs.createWriteStream('./tempy.mp4'))