Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

nodejs中 如何将readStream实例转base64

  fileToBase64 (pathOrReadStream) {
    let data
    if (typeof pathOrReadStream === 'string') {
      data = fs.createReadStream(pathOrReadStream)
    } else {
      data = pathOrReadStream
    }
    const instance = new Buffer(data)
    const base64 = instance.toString('base64')
    return base6464
    // const base64 = `data:image/png;base64,${data}}`
    // return base64
  },

以上代码, 如何修改


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TS写的,差不多意思

const stream2buffer = (stream: NodeJS.ReadableStream): Promise<Buffer> => {
  return new Promise((resolve, reject) => {
    if (!stream.readable) return resolve(Buffer.concat([]))
     
    const bufs: any = []

    const onData = (d: any) => bufs.push(d)

    const onEnd = (error: any) => {
      error ? reject(error) : resolve(Buffer.concat(bufs))
      clean()
    }
      
    const onClose = () => {
      resolve(Buffer.concat(bufs))
      clean()
    }

    const clean = () => {
      stream.removeListener('data', onData)
      stream.removeListener('end', onEnd)
      stream.removeListener('error', onEnd)
      stream.removeListener('close', onClose)
    }
      
    stream.on('data', onData)
    stream.on('end', onEnd)
    stream.on('error', onEnd)
    stream.on('close', onClose)
  })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...