|
| 1 | +'use strict'; |
| 2 | +const check = require('check-types'); |
| 3 | +const Readable = require('stream').Readable; |
| 4 | +const Promise = require('bluebird'); |
| 5 | + |
| 6 | +/** |
| 7 | + * Simple wrapper around node streams. |
| 8 | + */ |
| 9 | +class Stream { |
| 10 | + |
| 11 | + /** |
| 12 | + * @param {string} string |
| 13 | + * @return {Stream} |
| 14 | + * @throws Error |
| 15 | + */ |
| 16 | + static createReadStreamFromString(string) { |
| 17 | + |
| 18 | + check.assert.string(string, 'Missing input string.'); |
| 19 | + let s = new Readable(); |
| 20 | + s.push(string); |
| 21 | + s.push(null); |
| 22 | + return s; |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @param buffer |
| 27 | + * @return {Stream} |
| 28 | + */ |
| 29 | + static createReadStreamFromBuffer(buffer) { |
| 30 | + |
| 31 | + let s = new Readable(); |
| 32 | + s.push(buffer); |
| 33 | + s.push(null); |
| 34 | + return s; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @param {*} what |
| 39 | + * @return {boolean} |
| 40 | + */ |
| 41 | + static isStream(what) { |
| 42 | + |
| 43 | + return what instanceof Readable; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * This method reads stream into string, this method affects stream param - once read |
| 48 | + * it won't return anything when trying to read again. |
| 49 | + * @param {Stream} stream |
| 50 | + * @return {Promise<string>} |
| 51 | + * @throws Error |
| 52 | + */ |
| 53 | + static async readStreamToString(stream) { |
| 54 | + |
| 55 | + check.assert.instance(stream, Readable, 'Invalid file stream.'); |
| 56 | + |
| 57 | + let fileContent = ''; |
| 58 | + return new Promise((resolve, reject) => { |
| 59 | + stream.on('data', data => { |
| 60 | + fileContent += data.toString(); |
| 61 | + }); |
| 62 | + stream.on('end', () => { |
| 63 | + resolve(fileContent); |
| 64 | + }); |
| 65 | + stream.on('error', err => { |
| 66 | + reject(err); |
| 67 | + }); |
| 68 | + }); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +module.exports = Stream; |
0 commit comments