UNPKG

997 BJavaScriptView Raw
1const Readable = require('stream').Readable
2const Writable = require('stream').Writable
3const makePromise = require('makepromise')
4
5/**
6 * Write data to the stream, and resolve when it's ended.
7 * @param {Writable} ws write stream
8 * @param {string|Readable} source read source
9 * @returns {Promise<Writable>} A promise resolved with the writable stream, or rejected
10 * when an error occurred while reading or writing.
11 */
12async function write(ws, source) {
13 if (!(ws instanceof Writable)) {
14 throw new Error('Writable stream expected')
15 }
16 if (source instanceof Readable) {
17 if (!source.readable) {
18 throw new Error('Stream is not readable')
19 }
20 await new Promise((resolve, reject) => {
21 ws.on('finish', resolve)
22 ws.on('error', reject)
23 source.on('error', reject)
24 source.pipe(ws)
25 })
26 return ws
27 }
28 await makePromise(ws.end.bind(ws), source)
29 return ws
30}
31
32module.exports = write