### Install reading-time Package Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Install the reading-time library using npm. This is the initial step required before using the library in your project. ```bash npm install reading-time ``` -------------------------------- ### Install reading-time with npm Source: https://github.com/ngryman/reading-time/blob/master/README.md Install the reading-time package using npm. The --production flag ensures only necessary packages for production are installed. ```sh npm install reading-time --production ``` -------------------------------- ### Example Usage of readingTime Function Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md Demonstrates how to use the `readingTime` function and access its results, including minutes, time in milliseconds, and total word count. Ensure the 'reading-time' package is installed. ```typescript import readingTime from 'reading-time'; const result = readingTime('This is a sample article with multiple words.'); // result: { // minutes: 1, // time: 900, // words: { total: 9 } // } console.log(`Read this in ${result.minutes} minutes`); console.log(`${result.words.total} words`); ``` -------------------------------- ### Count Words Example Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md Demonstrates how to use the `countWords` function to get word count statistics from a given text. Ensure the `reading-time` package is imported. ```typescript import { countWords } from 'reading-time'; const stats = countWords('Hello world'); console.log(stats.total); // 2 ``` -------------------------------- ### Combine countWords and readingTimeWithCount Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md This example demonstrates how to combine `countWords` to get the word count and then use `readingTimeWithCount` with custom options for maximum control over the reading time calculation. ```typescript import { countWords, readingTimeWithCount } from 'reading-time'; const words = countWords(myText); const stats = readingTimeWithCount(words, { wordsPerMinute: 250 }); ``` -------------------------------- ### ReadingTimeStream Basic Usage Example Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Demonstrates how to pipe text data from a file stream into ReadingTimeStream and process the emitted word count. ```APIDOC ### Examples Basic streaming usage: ```typescript import { ReadingTimeStream, readingTimeWithCount } from 'reading-time'; import fs from 'fs'; const analyzer = new ReadingTimeStream(); fs.createReadStream('document.txt', { encoding: 'utf8' }) .pipe(analyzer) .on('data', (wordCount) => { // wordCount is { total: number } const stats = readingTimeWithCount(wordCount); console.log(`Reading time: ${stats.minutes} minutes`); }); ``` ``` -------------------------------- ### ReadingTimeStream Custom Word Boundary Example Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Shows how to provide a custom word boundary detection function to ReadingTimeStream for specific data formats like CSV. ```APIDOC Custom word boundary for comma-separated values: ```typescript const analyzer = new ReadingTimeStream({ wordBound: (char) => char === ',' || char === ' ' || char === '\n' }); fs.createReadStream('data.csv') .pipe(analyzer) .on('data', (count) => { console.log('Total fields:', count.total); }); ``` ``` -------------------------------- ### Node.js ES Modules Usage Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Calculate reading time for a given text using Node.js with ES Modules. This example shows the import syntax. ```javascript import readingTime from 'reading-time'; const stats = readingTime('Your article text here...'); ``` -------------------------------- ### Custom Word Boundaries for CSV and Identifiers Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Examples of defining custom word boundaries using the `wordBound` option. The first example handles comma-separated values, and the second handles underscore-separated identifiers. ```javascript countWords(csvLine, { wordBound: (char) => char === ',' || char === ' ' }); ``` ```javascript readingTime(documentation, { wordBound: (char) => /[\s_]/.test(char) }); ``` -------------------------------- ### Classic Usage in Node.js and Browser Source: https://github.com/ngryman/reading-time/blob/master/README.md Import and use the readingTime function to get reading time statistics. Note the different import paths for Node.js and browser environments. ```javascript // In Node.js const readingTime = require('reading-time'); // In the browser const readingTime = require('reading-time/lib/reading-time'); const stats = readingTime(text); // -> // stats: { // minutes: 1, // time: 60000, // words: {total: 200} // } console.log(`The reading time is: ${stats.minutes} min`); ``` -------------------------------- ### Adjust Reading Speed for Technical Content Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Configure a slower reading speed (150 WPM) for technical documentation to get a more accurate reading time estimate. ```typescript const stats = readingTime(technicalDocumentation, { wordsPerMinute: 150 // Slower for complex material }); ``` -------------------------------- ### Adjust Reading Speed with wordsPerMinute Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Configure the `wordsPerMinute` option to adjust the reading speed calculation for different content types. Examples show settings for slower, standard, and faster reading speeds. ```javascript readingTime(text, { wordsPerMinute: 150 }); ``` ```javascript readingTime(text, { wordsPerMinute: 200 }); ``` ```javascript readingTime(text, { wordsPerMinute: 250 }); ``` -------------------------------- ### Custom Word Boundary Detection Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md Example of using a custom `wordBound` function to define word boundaries, treating commas and spaces as delimiters for CSV data. ```typescript // Use custom word boundary for special formats readingTime(csvData, { wordBound: (char) => char === ',' || char === ' ' }); ``` -------------------------------- ### Adjust Reading Speed Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md Example of adjusting the reading speed for dense technical content by setting `wordsPerMinute` to 150. ```typescript import { readingTime } from 'reading-time'; // Adjust reading speed for dense technical content readingTime(text, { wordsPerMinute: 150 }); ``` -------------------------------- ### Basic Streaming Usage with ReadingTimeStream Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Demonstrates how to pipe a file stream through ReadingTimeStream to get the total word count. The 'data' event on the analyzer emits the word count, which is then used with `readingTimeWithCount` to calculate reading time. ```typescript import { ReadingTimeStream, readingTimeWithCount } from 'reading-time'; import fs from 'fs'; const analyzer = new ReadingTimeStream(); fs.createReadStream('document.txt', { encoding: 'utf8' }) .pipe(analyzer) .on('data', (wordCount) => { // wordCount is { total: number } const stats = readingTimeWithCount(wordCount); console.log(`Reading time: ${stats.minutes} minutes`); }); ``` -------------------------------- ### Get Reading Time with Default Options Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Use the default reading speed (200 WPM) and standard ANSI word boundaries by simply passing the text to the readingTime function. ```typescript import readingTime from 'reading-time'; const stats = readingTime('Your text here'); // Uses 200 WPM and standard ANSI word boundaries ``` -------------------------------- ### Define Custom Word Boundaries in JavaScript Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Use the `wordBound` option to define custom word boundaries for languages not supported by default. This example uses a regular expression to test for spaces. ```javascript readingTime(text, { wordBound: (char) => { // Return true if char is a boundary, false if part of a word return /\s/.test(char); // Example: space-based languages } }); ``` -------------------------------- ### Custom Word Boundary with ReadingTimeStream Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Illustrates configuring ReadingTimeStream with a custom `wordBound` function to define word boundaries, specifically for comma-separated values in a CSV file. This example treats commas, spaces, and newlines as word separators. ```typescript const analyzer = new ReadingTimeStream({ wordBound: (char) => char === ',' || char === ' ' || char === '\n' }); fs.createReadStream('data.csv') .pipe(analyzer) .on('data', (count) => { console.log('Total fields:', count.total); }); ``` -------------------------------- ### ReadingTimeStream Error Handling Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Provides an example of attaching an 'error' event listener to a ReadingTimeStream instance. This is crucial for robust error handling in production environments, as the stream itself does not throw errors but attempts to process invalid data. ```typescript analyzer.on('error', (err) => { console.error('Stream error:', err); }); ``` -------------------------------- ### Run Test Suite with npm Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Execute the project's test suite using npm commands. Includes options for linting, running specs, or both. ```bash npm test # Lint and run specs npm run spec # Run tests only npm run lint # Run ESLint only ``` -------------------------------- ### Importing readingTime Function Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Demonstrates how to import the default `readingTime` function in Node.js (ES Module and CommonJS) and how to include it in a browser environment. ```typescript // Node.js (ES Module) import readingTime from 'reading-time'; ``` ```javascript // Node.js (CommonJS) const readingTime = require('reading-time'); ``` ```html // Browser (Global) // readingTime is available globally ``` -------------------------------- ### Basic readingTime Usage Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Demonstrates the basic usage of the readingTime function with default options. It analyzes a sample text and logs the resulting statistics. ```typescript import readingTime from 'reading-time'; const stats = readingTime('This is a sample text with some words.'); console.log(stats); // Output: { minutes: 1, time: 900, words: { total: 9 } } ``` -------------------------------- ### Importing ReadingTimeStream Class Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Demonstrates how to import the `ReadingTimeStream` named export in Node.js using ES Module and CommonJS syntax. ```typescript // ES Module import { ReadingTimeStream } from 'reading-time'; ``` ```javascript // CommonJS const { ReadingTimeStream } = require('reading-time'); ``` -------------------------------- ### ReadingTimeStream Constructor Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Instantiate ReadingTimeStream to create a new reading time analyzer. It accepts an optional options object for configuration. ```APIDOC ## Constructor ```typescript new ReadingTimeStream(options?: Options) ``` Creates a new reading time analyzer stream. The stream accumulates word counts across all piped chunks and emits the total count when the stream ends. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | Options | no | {} | Configuration object for word counting | ### Configuration | Option | Type | Default | Description | |--------|------|---------|-------------| | wordBound | function | isAnsiWordBound | Custom word boundary detection function | | wordsPerMinute | number | 200 | Average reading speed (note: wordsPerMinute is accepted but not used by the stream itself; use [readingTimeWithCount](./reading-time.md#readingtimewithcount) on emitted data) | ``` -------------------------------- ### Streaming from Multiple Sources with ReadingTimeStream Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Shows how to use ReadingTimeStream to process multiple files sequentially. After processing the first file, a new ReadingTimeStream instance is created for the second file. ```typescript const analyzer = new ReadingTimeStream(); // First file fs.createReadStream('file1.txt', { encoding: 'utf8' }).pipe(analyzer); // Second file analyzer.on('data', (count1) => { console.log('File 1:', count1.total, 'words'); // Reset and process second file const analyzer2 = new ReadingTimeStream(); fs.createReadStream('file2.txt', { encoding: 'utf8' }) .pipe(analyzer2) .on('data', (count2) => { console.log('File 2:', count2.total, 'words'); }); }); ``` -------------------------------- ### Define Options Type Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md Defines the structure for configuration options, allowing customization of word boundaries and reading speed. ```typescript type Options = { wordBound?: (char: string) => boolean; wordsPerMinute?: number; } ``` -------------------------------- ### Browser Usage Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Calculate reading time in the browser by including the script and calling the readingTime function. Displays the result in minutes. ```html ``` -------------------------------- ### Browser Script Include Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Include this script tag in your HTML for browser usage. The library will be available globally as `readingTime` (default export only). ```html ``` -------------------------------- ### CommonJS Imports for reading-time Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Use these imports for CommonJS environments. They allow importing the default export and specific named exports. ```javascript const readingTime = require('reading-time'); const { countWords, readingTimeWithCount, ReadingTimeStream } = require('reading-time'); ``` -------------------------------- ### Importing readingTimeWithCount Function Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Illustrates how to import the `readingTimeWithCount` named export in Node.js using ES Module and CommonJS syntax. ```typescript // ES Module import { readingTimeWithCount } from 'reading-time'; ``` ```javascript // CommonJS const { readingTimeWithCount } = require('reading-time'); ``` -------------------------------- ### readingTime(text, options?) Source: https://github.com/ngryman/reading-time/blob/master/README.md Estimates the reading time for a given text. It returns an object containing the estimated minutes, exact time in milliseconds, and word count statistics. ```APIDOC ## readingTime(text, options?) ### Description Returns an object with `minutes`, `time` (in milliseconds), and `words`. ```ts type ReadingTimeResults = { minutes: number; time: number; words: WordCountStats; }; ``` ### Parameters - `text` (string) - The text to analyze. - `options` (object, optional) - `options.wordsPerMinute` (number, optional) - The words per minute an average reader can read (default: 200). - `options.wordBound` (function, optional) - A function that returns a boolean value depending on if a character is considered as a word bound (default: spaces, new lines and tabs). ``` -------------------------------- ### readingTimeWithCount(words, options?) Source: https://github.com/ngryman/reading-time/blob/master/README.md Calculates reading time based on pre-counted words. It returns an object with rounded minute stats and exact time in milliseconds. ```APIDOC ## readingTimeWithCount(words, options?) ### Description Returns an object with `minutes` (rounded minute stats) and `time` (exact time in milliseconds). Note that `readingTime(text, options) === readingTimeWithCount(countWords(text, options), options)`. ### Parameters - `words` (WordCountStats) - The word count stats. - `options` (object, optional) - `options.wordsPerMinute` (number, optional) - The words per minute an average reader can read (default: 200). ``` -------------------------------- ### Custom Word Boundary Detection Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Illustrates using readingTime with a custom wordBound function to define how word boundaries are identified, useful for non-standard text formats. ```typescript const stats = readingTime('word,word,word', { wordBound: (char) => char === ',' || char === ' ' || char === '\n' }); console.log(stats.words.total); // Counts words separated by commas ``` -------------------------------- ### Custom Reading Speed Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Shows how to use readingTime with a custom wordsPerMinute option to adjust the reading speed calculation. ```typescript const stats = readingTime('The quick brown fox jumps over the lazy dog.', { wordsPerMinute: 100 }); console.log(stats.minutes); // 1 minute at 100 WPM ``` -------------------------------- ### Adjust Reading Speed Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Configure the reading speed by setting the wordsPerMinute option. Use this to tailor the reading time calculation to different user preferences or content types. ```javascript readingTime(text, { wordsPerMinute: 150 }) // Slower readingTime(text, { wordsPerMinute: 200 }) // Default readingTime(text, { wordsPerMinute: 300 }) // Faster ``` -------------------------------- ### readingTime(text, opts) Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/INDEX.md Analyzes the provided text to calculate the estimated reading time and word count. It returns an object containing the minutes, time in milliseconds, and the total word count. ```APIDOC ## readingTime(text, opts) ### Description Analyzes the provided text to calculate the estimated reading time and word count. It returns an object containing the minutes, time in milliseconds, and the total word count. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **text** (string) - Required - The text content to analyze. - **opts** (Options) - Optional - Configuration options for analysis, such as wordsPerMinute and wordBound. ### Returns - **ReadingTimeResult** - An object containing the calculated reading time and word count. ### Example ```javascript import { readingTime } from 'reading-time'; const text = 'Here is some example text to analyze.'; const result = readingTime(text); console.log(result); // Output: { minutes: 1, time: 3000, words: 7 } ``` ``` -------------------------------- ### Importing countWords Function Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Shows how to import the `countWords` named export in Node.js using ES Module and CommonJS syntax. ```typescript // ES Module import { countWords } from 'reading-time'; ``` ```javascript // CommonJS const { countWords } = require('reading-time'); ``` -------------------------------- ### Node.js CommonJS Usage Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Calculate reading time for a given text using Node.js with CommonJS modules. The output includes minutes, time in milliseconds, and total words. ```javascript const readingTime = require('reading-time'); const stats = readingTime('Your article text here...'); console.log(stats); // Output: { minutes: 5, time: 300000, words: { total: 1000 } } ``` -------------------------------- ### readingTimeWithCount(words, opts) Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/INDEX.md Converts a given word count into an estimated reading time. It returns an object containing the calculated reading time in minutes and milliseconds. ```APIDOC ## readingTimeWithCount(words, opts) ### Description Converts a given word count into an estimated reading time. It returns an object containing the calculated reading time in minutes and milliseconds. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **words** (number) - Required - The total number of words. - **opts** (Options) - Optional - Configuration options, primarily `wordsPerMinute`. ### Returns - **ReadingTimeStats** - An object containing the calculated reading time in minutes and milliseconds. ### Example ```javascript import { readingTimeWithCount } from 'reading-time'; const wordCount = 100; const result = readingTimeWithCount(wordCount); console.log(result); // Output: { minutes: 1, time: 600000 } ``` ``` -------------------------------- ### TypeScript Options Type for Reading Time Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Defines the `Options` type for configuring the reading time library. It includes properties for words per minute and custom word boundaries. ```typescript type Options = { wordsPerMinute?: number; // Default: 200 wordBound?: (char: string) => boolean; // Default: space/newline/tab/carriage-return } ``` -------------------------------- ### Streaming Usage in Node.js Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/README.md Process an article from a file stream to calculate reading time. This is useful for large articles or real-time processing. ```javascript const { ReadingTimeStream, readingTimeWithCount } = require('reading-time'); const fs = require('fs'); const analyzer = new ReadingTimeStream(); fs.createReadStream('article.txt') .pipe(analyzer) .on('data', (wordCount) => { const stats = readingTimeWithCount(wordCount); console.log(`Reading time: ${stats.minutes} minutes`); }); ``` -------------------------------- ### Add Custom Language Support Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/INDEX.md Define custom word boundary detection for languages not natively supported by the library. This is achieved by providing a `wordBound` function within the options. ```typescript readingTime(text, { wordBound: (char) => { // Define your custom boundary detection return isYourLanguageBoundary(char); } }); ``` -------------------------------- ### ES Module Imports for reading-time Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Use these imports for ES Module environments. They provide access to the default export and named exports like countWords and ReadingTimeStream. ```typescript import readingTime, { countWords, readingTimeWithCount, ReadingTimeStream, Options, ReadingTimeStats, WordCountStats, ReadingTimeResult } from 'reading-time'; ``` -------------------------------- ### Process Large Files with Streaming Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md For large files, use the `ReadingTimeStream` to process the file content in chunks. Pipe the stream to `ReadingTimeStream` and then use `readingTimeWithCount` on the emitted data. ```typescript // Process large files with streaming import { ReadingTimeStream, readingTimeWithCount } from 'reading-time'; fs.createReadStream('file.txt') .pipe(new ReadingTimeStream()) .on('data', (count) => { const stats = readingTimeWithCount(count); }); ``` -------------------------------- ### Streaming with Custom Options Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Process text streams with custom reading speed and word boundary detection using ReadingTimeStream. The word count is then used to calculate reading time. ```typescript import { ReadingTimeStream, readingTimeWithCount } from 'reading-time'; import fs from 'fs'; const analyzer = new ReadingTimeStream({ wordsPerMinute: 175, wordBound: (char) => /[\s,;]/.test(char) // Commas and semicolons are boundaries }); fs.createReadStream('data.txt', { encoding: 'utf8' }) .pipe(analyzer) .on('data', (wordCount) => { const time = readingTimeWithCount(wordCount, { wordsPerMinute: 175 }); console.log(`${time.minutes} minutes`); }); ``` -------------------------------- ### Custom Word Boundary for Underscore-Separated Identifiers Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Implement a custom word boundary detection that includes underscores, spaces, and newlines, suitable for code documentation with underscore-separated identifiers. ```typescript const stats = readingTime(codeDocumentation, { wordBound: (char) => { // Treat spaces, newlines, and underscores as boundaries return /[ _]/.test(char); } }); ``` -------------------------------- ### Process Large Files with Streaming Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Processes large files using streams to estimate reading time and word count efficiently. ```APIDOC ## Process Large Files with Streaming ### Description Processes large files using streams to estimate reading time and word count efficiently. ### Method `fs.createReadStream(filePath).pipe(new ReadingTimeStream()).on('data', (count) => { ... })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { ReadingTimeStream, readingTimeWithCount } from 'reading-time'; import fs from 'fs'; fs.createReadStream('file.txt') .pipe(new ReadingTimeStream()) .on('data', (count) => { const stats = readingTimeWithCount(count); // Process stats }); ``` ### Response #### Success Response (200) - **count** (object) - An object containing word count data, typically used with `readingTimeWithCount`. #### Response Example ```json { "total": 1500 } ``` ``` -------------------------------- ### ReadingTimeStream Properties Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Access the accumulated statistics and configuration options of the ReadingTimeStream. ```APIDOC ### Property: stats ```typescript stats: WordCountStats // { total: number } ``` Accumulated word count statistics. Updated as each chunk is processed via the internal `_transform` method. Access this property if you need the count at any point during streaming (though it's also emitted when the stream ends). ### Property: options ```typescript options: Options ``` The configuration options passed to the constructor, stored for reference. ``` -------------------------------- ### Adjust Reading Speed Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/INDEX.md Configure the words per minute (WPM) to adjust the calculated reading time. Lower WPM is suitable for technical content, while higher WPM is for faster skimming. ```typescript // Slow (technical content): 150 WPM readingTime(text, { wordsPerMinute: 150 }) ``` ```typescript // Standard: 200 WPM (default) readingTime(text, { wordsPerMinute: 200 }) ``` ```typescript // Fast (skimming): 300 WPM readingTime(text, { wordsPerMinute: 300 }) ``` -------------------------------- ### countWords(text, options?) Source: https://github.com/ngryman/reading-time/blob/master/README.md Counts the words in a given text. It returns an object containing the total word count. ```APIDOC ## countWords(text, options?) ### Description Returns an object representing the word count stats. ```ts type WordCountStats = { total: number; }; ``` ### Parameters - `text` (string) - The text to analyze. - `options` (object, optional) - `options.wordBound` (function, optional) - A function that returns a boolean value depending on if a character is considered as a word bound (default: spaces, new lines and tabs). ``` -------------------------------- ### ReadingTimeStream Error Handling Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Provides guidance on attaching an 'error' event listener to ReadingTimeStream for robust error management. ```APIDOC ### Error Handling The stream does not throw errors. If invalid data is passed, the stream attempts to convert it to a string and count words. Always attach an `'error'` event listener for robust production use: ```typescript analyzer.on('error', (err) => { console.error('Stream error:', err); }); ``` ``` -------------------------------- ### Default Export: readingTime Function Signature Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md The default export `readingTime` takes a string of text and optional options to calculate reading time. It returns an object with minutes, time, and words properties. ```typescript export default function readingTime(text: string, options?: Options): ReadingTimeResult ``` -------------------------------- ### readingTime Function Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Analyzes text and returns reading time statistics including word count, estimated minutes, and total time in milliseconds. ```APIDOC ## readingTime(text, options?) ### Description Estimates the reading time of text content by counting words and calculating time based on average reading speed. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```typescript function readingTime(text: string, options?: Options): ReadingTimeResult ``` ### Parameters - **text** (string) - Required - The text content to analyze (supports plain text, markdown, and HTML). - **options** (Options) - Optional - Configuration object for word counting and reading speed. ### Return Type **ReadingTimeResult** ```typescript { minutes: number; // Rounded-up reading time in minutes (minimum 0) time: number; // Exact reading time in milliseconds words: WordCountStats; // Word count statistics } ``` The `words` property contains `{ total: number }` with the total word count from the input text. ### Configuration Options - **wordsPerMinute** (number) - Default: 200 - Average reading speed in words per minute. - **wordBound** (function) - Default: isAnsiWordBound - Custom function to identify word boundaries. ### Examples #### Basic Usage ```typescript import readingTime from 'reading-time'; const stats = readingTime('This is a sample text with some words.'); console.log(stats); // Output: { minutes: 1, time: 900, words: { total: 9 } } ``` #### Custom Reading Speed ```typescript const stats = readingTime('The quick brown fox jumps over the lazy dog.', { wordsPerMinute: 100 }); console.log(stats.minutes); // 1 minute at 100 WPM ``` #### Custom Word Boundary Detection ```typescript const stats = readingTime('word,word,word', { wordBound: (char) => char === ',' || char === ' ' || char === '\n' }); console.log(stats.words.total); // Counts words separated by commas ``` ### Error Handling Does not throw errors; handles all input gracefully, including empty strings (returns `minutes: 0, time: 0`). ``` -------------------------------- ### Custom Word Boundary for Non-Latin Script (Thai) Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Configure a custom word boundary function to correctly identify word boundaries in Thai script by checking specific Unicode ranges and whitespace. ```typescript const stats = readingTime(thaiText, { wordBound: (char) => { // Thai script example: treat specific Unicode ranges as words const code = char.charCodeAt(0); return (code >= 0x0E00 && code <= 0x0E7F) || /\s/.test(char); } }); ``` -------------------------------- ### Define Custom Word Separators Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/INDEX.md Customize word boundary detection using the `wordBound` option. This is useful for parsing non-standard text formats like CSV or code documentation with specific separators. ```typescript // Comma-separated values countWords(csvLine, { wordBound: (c) => c === ',' || c === ' ' }) ``` ```typescript // Underscores and spaces (code documentation) readingTime(doc, { wordBound: (c) => /[ _]/.test(c) }) ``` -------------------------------- ### countWords Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Counts the number of words in a given text. It supports plain text, markdown, HTML, and CJK languages, handling various punctuation and whitespace scenarios. ```APIDOC ## countWords(text, options?) ### Description Counts the number of words in text. Handles plain text, markdown, HTML, and CJK (Chinese, Japanese, Korean) languages. ### Method ```typescript function countWords(text: string, options?: Options): WordCountStats ``` ### Parameters #### Path Parameters - **text** (string) - Required - The text to analyze - **options** (Options) - Optional - Configuration object for word boundary detection ### Return Type **WordCountStats** ```typescript { total: number; // Total word count } ``` ### Configuration Options #### Option - **wordBound** (function) - Optional - Custom function to identify word boundaries; receives a character and returns true if it's a boundary. Default: `isAnsiWordBound` ### Behavior - **ANSI languages**: Words are separated by spaces, newlines, tabs, or carriage returns - **CJK languages**: Each character is treated as a word; punctuation is handled specially - **Mixed content**: Correctly counts both CJK and Latin words in the same text - **Whitespace**: Leading and trailing whitespace is automatically trimmed - **Punctuation**: ASCII and CJK punctuation is stripped from counts ### Examples Basic word counting: ```typescript import { countWords } from 'reading-time'; const stats = countWords('Hello world example text'); console.log(stats); // { total: 4 } ``` CJK text counting: ```typescript const stats = countWords('你好世界'); // Chinese console.log(stats); // { total: 4 } const stats2 = countWords('こんにちは'); // Japanese console.log(stats2); // { total: 5 } ``` Mixed content (Latin + CJK): ```typescript const stats = countWords('Hello 世界 world'); console.log(stats); // { total: 4 } ``` ``` -------------------------------- ### Estimate Reading Time Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Use this function to estimate the reading time for a given text. It returns an object containing the estimated minutes, total milliseconds, and word count. ```typescript // Estimate reading time import readingTime from 'reading-time'; const stats = readingTime('Your article text...'); // → { minutes: 5, time: 300000, words: { total: 1000 } } ``` -------------------------------- ### Function Signature for wordBound Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Defines the expected signature for a custom word boundary function. It accepts a single character and returns a boolean indicating if it's a word boundary. ```typescript (char: string) => boolean ``` -------------------------------- ### Calculate Time from Word Count Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Use `readingTimeWithCount` to calculate the estimated reading time when you already have the total word count. This is useful if you've pre-calculated word counts. ```typescript // Calculate time from word count import { readingTimeWithCount } from 'reading-time'; const time = readingTimeWithCount({ total: 200 }); // → { minutes: 1, time: 60000 } ``` -------------------------------- ### Estimate Reading Time Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Estimates the reading time for a given text. It returns an object containing the estimated minutes, total milliseconds, and word count. ```APIDOC ## Estimate Reading Time ### Description Estimates the reading time for a given text. It returns an object containing the estimated minutes, total milliseconds, and word count. ### Method `readingTime(text: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import readingTime from 'reading-time'; const stats = readingTime('Your article text...'); // → { minutes: 5, time: 300000, words: { total: 1000 } } ``` ### Response #### Success Response (200) - **minutes** (number) - Estimated reading time in minutes. - **time** (number) - Estimated reading time in milliseconds. - **words** (object) - Object containing word count details. - **total** (number) - Total number of words. #### Response Example ```json { "minutes": 5, "time": 300000, "words": { "total": 1000 } } ``` ``` -------------------------------- ### Calculate Reading Time with Custom Speed Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Customize the reading speed (words per minute) to adjust the calculated reading time. This is useful for tailoring the estimate to specific audiences or content types. ```typescript const stats = readingTimeWithCount({ total: 300 }, { wordsPerMinute: 100 }); console.log(stats); // { minutes: 3, time: 180000 } ``` -------------------------------- ### Calculate Time from Word Count Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Calculates the reading time based on a provided word count. ```APIDOC ## Calculate Time from Word Count ### Description Calculates the reading time based on a provided word count. ### Method `readingTimeWithCount(options: { total: number })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { readingTimeWithCount } from 'reading-time'; const time = readingTimeWithCount({ total: 200 }); // → { minutes: 1, time: 60000 } ``` ### Response #### Success Response (200) - **minutes** (number) - Estimated reading time in minutes. - **time** (number) - Estimated reading time in milliseconds. #### Response Example ```json { "minutes": 1, "time": 60000 } ``` ``` -------------------------------- ### Stream Processing with ReadingTimeStream Source: https://github.com/ngryman/reading-time/blob/master/README.md Utilize ReadingTimeStream for processing readable streams, such as files. The stream emits word counts which can then be used to calculate reading time. ```javascript const {ReadingTimeStream, readingTimeWithCount} = require('reading-time'); const analyzer = new ReadingTimeStream(); fs.createReadStream('foo') .pipe(analyzer) .on('data', (count) => { console.log(`The reading time is: ${readingTimeWithCount(count).minutes} min`); }); ``` -------------------------------- ### Custom Word Boundaries Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Define custom word boundaries using the wordBound option. This allows for specific character-based separation of words, overriding default behavior. ```javascript readingTime(text, { wordBound: (char) => char === ',' || char === ' ' // Custom separators }) ``` -------------------------------- ### ReadingTimeStream Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md A stream transform class for calculating reading time on chunks of data. Extends Node.js stream.Transform. ```APIDOC ## ReadingTimeStream (Class) ### Description A stream transform class for calculating reading time on chunks of data. ### Constructor ```typescript new ReadingTimeStream(options?: Options) ``` ### Parameters #### Path Parameters - **options** (Options) - Optional - Configuration options for the stream. ### Extends `stream.Transform` (Node.js) ``` -------------------------------- ### readingTime Function Signature Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Defines the signature for the readingTime function, indicating its input parameters and return type. ```typescript function readingTime(text: string, options?: Options): ReadingTimeResult ``` -------------------------------- ### ReadingTimeStream Methods Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time-stream.md Internal methods used by the Node.js stream API to process data chunks and manage stream lifecycle. ```APIDOC ### Methods #### _transform(chunk, encoding, callback) ```typescript _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void ``` Internal Transform stream method called for each chunk. Counts words in the chunk and accumulates the total in `this.stats`. Does not emit data on each chunk; only the final accumulated count is emitted on stream end. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | chunk | Buffer | The data chunk to process | | encoding | BufferEncoding | The encoding of the chunk (e.g., 'utf8') | | callback | TransformCallback | Node.js stream callback to signal completion | #### _flush(callback) ```typescript _flush(callback: TransformCallback): void ``` Internal Transform stream method called when the stream ends. Emits the accumulated `stats` object and signals completion. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | callback | TransformCallback | Node.js stream callback to signal completion | ``` -------------------------------- ### ReadingTimeStats Type Definition Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md Represents reading time statistics without word count. It includes the exact reading time in milliseconds and the rounded reading time in minutes. ```typescript type ReadingTimeStats = { time: number; minutes: number; } ``` -------------------------------- ### Named Export: ReadingTimeStream Class Signature Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md The `ReadingTimeStream` is a named export that extends Node.js's `stream.Transform` class, allowing for stream-based processing of text to calculate reading time. It can be instantiated with optional options. ```typescript export default class ReadingTimeStream extends Transform ``` -------------------------------- ### readingTimeWithCount Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Calculates reading time based on pre-counted words. This function is useful when word counts are already available. ```APIDOC ## readingTimeWithCount (Function) ### Description Calculates reading time based on pre-counted words. ### Signature ```typescript readingTimeWithCount(words: WordCountStats, options?: Options): ReadingTimeStats ``` ### Parameters #### Path Parameters - **words** (WordCountStats) - Required - An object containing the total word count. - **options** (Options) - Optional - Configuration options for reading time calculation. ### Returns `ReadingTimeStats` with `{ minutes: number, time: number }`. ``` -------------------------------- ### Named Export: readingTimeWithCount Function Signature Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md The `readingTimeWithCount` function is a named export that accepts pre-counted words and optional options to calculate reading time statistics. It returns an object with `minutes` and `time` properties. ```typescript export function readingTimeWithCount( words: WordCountStats, options?: Options ): ReadingTimeStats ``` -------------------------------- ### Calculate Reading Time from Word Count Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Use this snippet to calculate reading time statistics when you already have the total word count. It uses the default reading speed of 200 words per minute. ```typescript import { readingTimeWithCount } from 'reading-time'; const wordCount = { total: 200 }; const stats = readingTimeWithCount(wordCount); console.log(stats); // { minutes: 1, time: 60000 } ``` -------------------------------- ### ReadingTimeStats Type Definition Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md Represents the calculated reading time statistics. It includes the estimated time in seconds and minutes. ```typescript export type ReadingTimeStats = { time: number; minutes: number; } ``` -------------------------------- ### Count Words Only Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/00-START-HERE.md Counts only the total number of words in a given text. ```APIDOC ## Count Words Only ### Description Counts only the total number of words in a given text. ### Method `countWords(text: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { countWords } from 'reading-time'; const count = countWords('text'); // → { total: 50 } ``` ### Response #### Success Response (200) - **total** (number) - Total number of words. #### Response Example ```json { "total": 50 } ``` ``` -------------------------------- ### TypeScript Type Imports Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/EXPORT_MAP.md TypeScript type imports work with both ES Module and CommonJS systems, allowing you to import types like Options and ReadingTimeResult. ```typescript import type { Options, ReadingTimeResult } from 'reading-time'; ``` -------------------------------- ### ReadingTimeStream Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/INDEX.md A stream processor designed for handling large files efficiently. It accumulates word counts across chunks and emits a single result when the stream ends. ```APIDOC ## ReadingTimeStream ### Description A stream processor designed for handling large files efficiently. It accumulates word counts across chunks and emits a single result when the stream ends. This class is part of the Node.js API. ### Methods - **_transform(chunk, encoding, callback)**: Processes incoming data chunks. - **_flush(callback)**: Called when the stream has finished processing all chunks. ### Purpose To provide a memory-efficient way to calculate reading time for large text inputs by processing them in chunks using Node.js streams. ### Example ```javascript import { ReadingTimeStream } from 'reading-time/stream'; import * as fs from 'fs'; const stream = new ReadingTimeStream(); const fileStream = fs.createReadStream('large_file.txt'); fileStream.pipe(stream).on('data', (data) => { console.log('Reading time for file:', data); }); ``` ``` -------------------------------- ### Count Words in Text Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/api-reference/reading-time.md Use this function to count words in various text formats including plain text, markdown, HTML, and CJK languages. It handles different word boundary definitions and punctuation stripping. ```typescript import { countWords } from 'reading-time'; const stats = countWords('Hello world example text'); console.log(stats); // { total: 4 } ``` ```typescript const stats = countWords('你好世界'); // Chinese console.log(stats); // { total: 4 } ``` ```typescript const stats2 = countWords('こんにちは'); // Japanese console.log(stats2); // { total: 5 } ``` ```typescript const stats = countWords('Hello 世界 world'); console.log(stats); // { total: 4 } ``` -------------------------------- ### Custom Word Boundary for CSV Data Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/configuration.md Define a custom word boundary function to treat commas, spaces, and newlines as separators in CSV data, rather than characters within words. ```typescript const stats = countWords(csvLine, { wordBound: (char) => char === ',' || char === ' ' || char === '\n' }); // Treats commas as separators instead of characters ``` -------------------------------- ### ReadingTimeResult Type Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md The complete reading time analysis result, combining time statistics and word count. This is the return type of the main readingTime function. ```APIDOC ## ReadingTimeResult ```typescript type ReadingTimeResult = ReadingTimeStats & { words: WordCountStats; } ``` Complete reading time analysis result combining time statistics and word count. This is the return type of the main [readingTime](./api-reference/reading-time.md#readingtime) function. ### Fields Inherits all fields from [ReadingTimeStats](./types.md#readingtimestats) plus: | Field | Type | Description | |-------|------|-------------| | time | number | Exact reading time in milliseconds (from ReadingTimeStats) | | minutes | number | Rounded reading time in minutes (from ReadingTimeStats) | | words | WordCountStats | Word count statistics; contains `{ total: number }` | ### Returned By - [readingTime](./api-reference/reading-time.md#readingtime) ### Examples ```typescript import readingTime from 'reading-time'; const result = readingTime('This is a sample article with multiple words.'); // result: { // minutes: 1, // time: 900, // words: { total: 9 } // } console.log(`Read this in ${result.minutes} minutes`); console.log(`${result.words.total} words`); ``` ``` -------------------------------- ### Define WordBoundFunction Type Alias Source: https://github.com/ngryman/reading-time/blob/master/_autodocs/types.md This type alias represents a function used for detecting word boundaries. It takes a single character as input and returns a boolean. Custom implementations can be provided via the `wordBound` option. ```typescript type WordBoundFunction = Options['wordBound'] ```