{"name":"peek-readable","version":"6.0.2","keywords":["readable","buffer","stream","read"],"author":{"url":"https://github.com/Borewit","name":"Borewit"},"license":"MIT","_id":"peek-readable@6.0.2","homepage":"https://github.com/Borewit/peek-readable#readme","bugs":{"url":"https://github.com/Borewit/peek-readable/issues"},"dist":{"shasum":"35e704b8ad0576b41a4ba0f3c32cbcf53bac83fe","tarball":"http://registry-npm.ywwl.com/peek-readable/download/peek-readable-6.0.2.tgz","fileCount":19,"integrity":"sha512-XDaPdoABVmcY4PzDFAEBbCvdu8daWWMrCsDkCgMLqPHNFoXqUvGsfeBF6fndW5WUrh535psyZqOX4UfwMczrpw==","signatures":[{"sig":"MEUCIBiQY2P2dviHnGfcluXHexw7hjHFv9op44SXJfJTnoseAiEApT8yPNu0PBIfb0vnlruCPo7VDi7XUWFZ966zx3mPpbI=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":25575,"size":6823,"noattachment":false,"key":"/peek-readable/-/peek-readable-6.0.2.tgz"},"type":"module","types":"lib/index.d.ts","engines":{"node":">=18"},"exports":"./lib/index.js","funding":{"url":"https://github.com/sponsors/Borewit","type":"github"},"gitHead":"407b7dbd861fc4750df91b6c69b18e4267d03f80","scripts":{"lint":"yarn run lint-md && yarn run lint-ts","test":"mocha","build":"npm run clean && npm run compile","clean":"del-cli 'lib/**/*.js' 'lib/**/*.js.map' 'lib/**/*.d.ts' 'test/**/*.js' 'test/**/*.js.map' 'coverage' '.nyc_output'","start":"yarn run compile && yarn run lint && yarn run cover-test","compile":"yarn run compile-src && yarn run compile-test","lint-md":"remark -u preset-lint-recommended .","lint-ts":"biome check","compile-src":"tsc -p lib","compile-test":"tsc -p test","test-coverage":"c8 npm run test"},"_npmUser":{"name":"borewit","email":"borewit@xs4all.nl"},"repository":{"url":"git+https://github.com/Borewit/peek-readable.git","type":"git"},"_npmVersion":"10.9.2","description":"Read and peek from a readable stream","directories":{},"_nodeVersion":"22.13.1","_hasShrinkwrap":false,"packageManager":"yarn@4.6.0","devDependencies":{"c8":"^10.1.3","chai":"^5.1.2","mocha":"^11.1.0","del-cli":"^6.0.0","ts-node":"^10.9.2","remark-cli":"^12.0.1","typescript":"^5.7.3","@types/chai":"^5.0.1","@types/node":"^22.10.10","@types/mocha":"^10.0.10","@biomejs/biome":"1.9.4","chai-as-promised":"^8.0.1","source-map-support":"^0.5.21","@types/chai-as-promised":"^8.0.1","remark-preset-lint-recommended":"^7.0.0"},"_npmOperationalInternal":{"tmp":"tmp/peek-readable_6.0.2_1738245022323_0.5073819007277245","host":"s3://npm-registry-packages-npm-production"},"readme":"[![CI](https://github.com/Borewit/peek-readable/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/Borewit/peek-readable/actions/workflows/ci.yml)\r\n[![CodeQL](https://github.com/Borewit/peek-readable/actions/workflows/github-code-scanning/codeql/badge.svg?branch=master)](https://github.com/Borewit/peek-readable/actions/workflows/github-code-scanning/codeql)\r\n[![NPM version](https://badge.fury.io/js/peek-readable.svg)](https://npmjs.org/package/peek-readable)\r\n[![npm downloads](http://img.shields.io/npm/dm/peek-readable.svg)](https://npmcharts.com/compare/peek-readable?start=600&interval=30)\r\n[![Coverage Status](https://coveralls.io/repos/github/Borewit/peek-readable/badge.svg?branch=master)](https://coveralls.io/github/Borewit/peek-readable?branch=master)\r\n[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d4b511481b3a4634b6ca5c0724407eb9)](https://www.codacy.com/gh/Borewit/peek-readable/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Borewit/peek-readable&amp;utm_campaign=Badge_Grade)\r\n[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/peek-readable/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/peek-readable?targetFile=package.json)\r\n\r\n# peek-readable\r\n\r\nA promise based asynchronous stream reader, which makes reading from a stream easy.\r\n\r\nAllows to read and peek from a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams)\r\n\r\nThis module is used by [strtok3](https://github.com/Borewit/strtok3)\r\n\r\nThe `peek-readable` contains one class: `StreamReader`, which reads from a [stream.Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable).\r\n\r\n- Class `StreamReader` is used to read from Node.js [stream.Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable).\r\n- Class `WebStreamByobReader` is used to read from [ReadableStream<Uint8Array>](https://developer.mozilla.org/docs/Web/API/ReadableStream)\r\n\r\n## Compatibility\r\n\r\nModule: version 5 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).\r\nJavaScript is compliant with [ECMAScript 2019 (ES10)](https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019).\r\nRequires a modern browser or Node.js ≥ 18 engine.\r\n\r\nFor TypeScript CommonJs backward compatibility, you can use [load-esm](https://github.com/Borewit/load-esm).\r\n\r\n## Usage\r\n\r\n### Installation\r\n\r\n```shell script\r\nnpm install --save peek-readable\r\n```\r\n\r\n## API Documentation\r\n\r\nBoth `StreamReader` and `WebStreamByobReader` implement the [IStreamReader interface](#istreamreader-interface).\r\n\r\n### `IStreamReader` Interface\r\n\r\nThe `IStreamReader` interface defines the contract for a stream reader,\r\nwhich provides methods to read and peek data from a stream into a `Uint8Array` buffer.\r\nThe methods are asynchronous and return a promise that resolves with the number of bytes read.\r\n\r\n#### Methods\r\n\r\n##### `peek` function\r\nThis method allows you to inspect data from the stream without advancing the read pointer.\r\nIt reads data into the provided Uint8Array at a specified offset but does not modify the stream's internal position, \r\nallowing you to look ahead in the stream.\r\n\r\n```ts  \r\npeek(buffer: Uint8Array, offset: number, length: number): Promise<number>\r\n```\r\n\r\nParameters:\r\n- `buffer`: `Uint8Array`: The buffer into which the data will be peeked.\r\n  This is where the peeked data will be stored.\r\n- `maybeBeLess`: If true, the buffer maybe partially filled.\r\n\r\nReturns `Promise<number>`: \r\nA promise that resolves with the number of bytes actually peeked into the buffer. \r\nThis number may be less than the requested length if the end of the stream is reached.\r\n\r\n##### `read` function\r\n```ts  \r\nread(buffer: Uint8Array, offset: number, length: number): Promise<number>\r\n```\r\n\r\nParameters:\r\n- `buffer`: `Uint8Array`: The buffer into which the data will be read.\r\n  This is where the read data will be stored.\r\n- `maybeBeLess`: If true, the buffer maybe partially filled.\r\n\r\nReturns `Promise<number>`:\r\nA promise that resolves with the number of bytes actually read into the buffer.\r\nThis number may be less than the requested length if the end of the stream is reached.\r\n\r\n##### `abort` function\r\n\r\nAbort active asynchronous operation (`read` or `peak`) before it has completed.\r\n\r\n```ts  \r\nabort(): Promise<void>\r\n```\r\n\r\n## Examples\r\n\r\nIn the following example we read the first 16 bytes from a stream and store them in our buffer.\r\nSource code of examples can be found [here](test/examples.ts).\r\n\r\n```js\r\nimport fs from 'node:fs';\r\nimport { StreamReader } from 'peek-readable';\r\n\r\n(async () => {\r\n  const readable = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');\r\n  const streamReader = new StreamReader(readable);\r\n  const uint8Array = new Uint8Array(16);\r\n  const bytesRead = await streamReader.read(uint8Array);;\r\n  // buffer contains 16 bytes, if the end-of-stream has not been reached\r\n})();\r\n```\r\n\r\nEnd-of-stream detection:\r\n```js\r\n(async () => {\r\n\r\n  const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');\r\n  const streamReader = new StreamReader(fileReadStream);\r\n  const buffer = Buffer.alloc(16); // or use: new Uint8Array(16);\r\n\r\n  try {\r\n    await streamReader.read(buffer);\r\n    // buffer contains 16 bytes, if the end-of-stream has not been reached\r\n  } catch(error) {\r\n    if (error instanceof EndOfStreamError) {\r\n      console.log('End-of-stream reached');\r\n    }\r\n  }\r\n})();\r\n```\r\n\r\nWith `peek` you can read ahead:\r\n```js\r\nimport fs from 'node:fs';\r\nimport { StreamReader } from 'peek-readable';\r\n\r\nfunction closeNodeStream(stream: ReadStream): Promise<void> {\r\n  return new Promise<void>((resolve, reject) => {\r\n    stream.close(err => {\r\n      if(err)\r\n        reject(err);\r\n      else\r\n        resolve();\r\n    });\r\n  })\r\n}\r\n\r\n(async () => {\r\n\r\n  const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');\r\n  try {\r\n    const streamReader = new StreamReader(fileReadStream);\r\n    try {\r\n      const buffer = Buffer.alloc(20);\r\n\r\n      let bytesRead = await streamReader.peek(buffer.subarray(0, 3));\r\n      if (bytesRead === 3 && buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {\r\n        console.log('This is a JPEG file');\r\n      } else {\r\n        throw Error('Expected a JPEG file');\r\n      }\r\n\r\n      bytesRead = await streamReader.read(buffer); // Read JPEG header\r\n      if (bytesRead === 20) {\r\n        console.log('Got the JPEG header');\r\n      } else {\r\n        throw Error('Failed to read JPEG header');\r\n      }\r\n    } finally {\r\n      await streamReader.close(); // Release fileReadStream\r\n    }    \r\n  } finally {\r\n    await closeNodeStream(fileReadStream);\r\n  }\r\n\r\n\r\n})();\r\n```\r\n\r\n## Licence\r\n\r\nThis project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed.\r\n","publish_time":1738245022511,"maintainers":[{"name":"borewit","email":"borewit@xs4all.nl"}],"_cnpm_publish_time":1738245022511,"dist-tags":{"beta":"5.4.0-beta.7","esm":"5.0.0-alpha.5","latest":"7.0.0"}}