Sharp.js无法通过管道传输到流。可写吗?

时间:2020-09-03 03:19:09

标签: javascript node.js stream sharp nodejs-stream

在“精确”上找到:“ ^ 0.26.0”

由于某些原因,此不起作用

const readableStream = new stream.Readable({
    objectMode: true,
    read() {}
})

class FileSwitch extends stream.Writable {
    constructor(options, folder) {
        super(options)
        this.i = 0
    }

    _write(chunk, encoding, next) {
        console.log(this.i)
        this.i++
        next()
    }
}

var png = sharp().png()
var fileswitch = new FileSwitch();
readableStream.pipe(png).pipe(fileswitch)

无输出

但是由于某些原因,它确实可以工作:

const readableStream = new stream.Readable({
    objectMode: true,
    read() {}
})

class FileSwitch extends stream.Writable {
    constructor(options, folder) {
        super(options)
        this.i = 0
    }

    _write(chunk, encoding, next) {
        console.log(this.i)
        this.i++
        next()
    }
}

var png = sharp().png()
var fileswitch = new FileSwitch();
readableStream.pipe(png.pipe(fileswitch))
>>> 0
>>> 1
>>> 2

使用setInterval()以1秒的间隔将可读流推入新的字符串数据块。

我不是要向可写流公开功能吗?文档说该设置应该可以工作:)

更新

在@Matt的评论中添加了建议。

const readableStream = new stream.Readable({
    objectMode: true,
    read() {}
})

class FileSwitch extends stream.Writable {
    constructor(options, folder) {
        super(options)
        this.i = 0
    }

    _write(chunk, encoding, next) {
        console.log(this.i)
        this.i++
        next()
    }
}

readableStream.on('error', listener => {
    console.log(listener)
})

readableStream.on('warning', listener => {
    console.log(listener)
})

var png = sharp().png()
var fileswitch = new FileSwitch();
readableStream.pipe(png).pipe(fileswitch)

无输出

1 个答案:

答案 0 :(得分:0)

被推送到可读流的数据块不是有效的图像格式,因此无法将Sharp转换为png。将错误事件侦听器添加到png转换器会显示正确的错误。