Skip to content

Commit

Permalink
Throw error when stream is not defined
Browse files Browse the repository at this point in the history
  • Loading branch information
jferrerol committed Dec 14, 2020
1 parent 75e7da3 commit ce974c5
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class InvalidStreamError extends Error {}
5 changes: 5 additions & 0 deletions lib/stream-to-buffer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { BufferableStream } from './buffer-stream';
import { InvalidStreamError } from './error';

/**
* @Method: Returns the content of the readable stream as a buffer
* @Param {NodeJS.ReadableStream}
* @Return {Promise<Buffer>}
*/
export async function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer> {
if (!stream) {
throw new InvalidStreamError('stream is not defined');
}

const bufferableStream = new BufferableStream();

return new Promise((resolve: (data: Buffer) => void, reject: (error: Error) => void): void => {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@jorgeferrero/stream-to-buffer",
"version": "2.0.5",
"version": "2.0.6",
"description": "A promise based npm package that converts a node.js ReadStream to buffer",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
12 changes: 12 additions & 0 deletions test/stream-to-buffer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,24 @@ import { Readable } from 'stream';
import { streamToBuffer } from '../lib/stream-to-buffer';

describe('streamToBuffer', (): void => {
const mockValue = (value: any): any => value;

it('should return the read stream content as a Buffer', async (): Promise<void> => {
const testData = Buffer.from('test_data');

await expect(streamToBuffer(fs.createReadStream('testdata/small-file'))).resolves.toEqual(testData);
});

it('should throw an error when the stream is not defined', async (): Promise<void> => {
const stream = mockValue(undefined);
await expect(streamToBuffer(stream)).rejects.toThrow('stream is not defined');
});

it('should throw an error when the stream is null', async (): Promise<void> => {
const stream = mockValue(null);
await expect(streamToBuffer(stream)).rejects.toThrow('stream is not defined');
});

it('should throw an error when the error event is emitted', async (): Promise<void> => {
const fakeError = new Error('fake');
const readStream = new Readable({
Expand Down

0 comments on commit ce974c5

Please sign in to comment.