Git Product home page Git Product logo

reading-time's Introduction

reading-time

NPM Build Status


Medium's like reading time estimation.

reading-time helps you estimate how long an article will take to read. It works perfectly with plain text, but also with markdown or html.

Note that it's focused on performance and simplicity, so the number of words it will extract from other formats than plain text can vary a little. But this is an estimation right?

Installation

npm install reading-time --production

Usage

Classic

// 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`);
πŸ™‹β€β™‚οΈ Why different imports for Node.js and the browser?

This library is primarily for Node.js. The entrypoint also exports a ReadingTimeStream class which is, without polyfills, not supported in browsers. A simple workaround is to import the underlying lib/reading-time module.

Note that in the upcoming 2.0.0 version, this won't be necessary anymore.

Stream

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`);
  });
πŸ™‹β€β™‚οΈ Can I use this in the browser?

Yes. You need to provide the appropriate polyfills. Please refer to your bundler's documentation.

API

readingTime(text, options?)

Returns an object with minutes, time (in milliseconds), and words.

type ReadingTimeResults = {
  minutes: number;
  time: number;
  words: WordCountStats;
};
  • text: the text to analyze
  • options (optional)
    • options.wordsPerMinute: (optional) the words per minute an average reader can read (default: 200)
    • options.wordBound: (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)

countWords(text, options?)

Returns an object representing the word count stats:

type WordCountStats = {
  total: number;
};
  • text: the text to analyze
  • options (optional)
    • options.wordBound: (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?)

Returns an object with minutes (rounded minute stats) and time (exact time in milliseconds).

  • words: the word count stats
  • options (optional)
    • options.wordsPerMinute: (optional) the words per minute an average reader can read (default: 200)

Note that readingTime(text, options) === readingTimeWithCount(countWords(text, options), options).

Help wanted!

This library has been optimized for alphabetical languages and CJK languages, but may not behave correctly for other languages that don't use spaces for word bounds. If you find the behavior of this library to deviate significantly from your expectation, issues or contributions are welcomed!

Other projects

  • Fauda: configuration made simple.
  • Badge Size: Displays the size of a given file in your repository.
  • Commitizen Emoji: Commitizen adapter formatting commit messages using emojis.

reading-time's People

Contributors

cgbur avatar chud-uk avatar deadcoder0904 avatar dependabot[bot] avatar greenkeeper[bot] avatar johnpapa avatar josh-cena avatar moonmeister avatar ngryman avatar thom4parisot avatar xapphire13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reading-time's Issues

v1.5.0 requires additional Webpack config

Just jumping in to say that, with my current setup, v1.4.0 worked fine without any changes, but updating to v1.5.0 required me to add the following to my webpack config:

node: {
  global: true
},
resolve: {
  fallback: {
    stream: 'stream-browserify'
  }
},
plugins: [
  new webpack.ProvidePlugin({
    process: 'process/browser',
    Buffer: ['buffer', 'Buffer']
  })
]

and had to install stream-browserify.

The problematic line was const Transform = require('stream').Transform, but this line is also present in v1.4.0. This is a node core package, so it is expected for some kind of polyfill to be needed, but for some strange reason, v1.4.0 just works without any particular configuration change. πŸ€·β€β™‚οΈ

Originally posted by @miguelcobain in #38 (comment)

TypeScript definitions

declare module "reading-time" {
    interface ReadingTimeOptions {
        wordsPerMinute?: number
        wordBound?: string
    }

    interface ReadingTimeStats {
        text: string
        time: number
        words: number
        minutes: number
    }

    function readingTime(text: string, options?: ReadingTimeOptions): ReadingTimeStats

    namespace readingTime { }

    export = readingTime
}

require('reading-time/stream') is not found

When I am using following line

     const readingTime = require('reading-time/stream');

I am getting an error module reading-time/stream not found. Could you please show an example how can we use that

Thank You
Sourabh Somani

Help us complete the word counting algorithm!

Word counting is not as trivial as it seems. Most languages use spaces to separate words, but languages like Chinese and Japanese treat each character as a word, and there are no spaces. Therefore, we treat them slightly differently from Latin languages.

If you:

  1. Know a non-CJK language that doesn't use spaces to separate words
  2. Know the exact unicode range of characters that can be "standalone words"
  3. Have backed up arguments about whether Katakana characters should be counted as words (see #35 (comment))
  4. Other valuable comments about our implementation

Please don't hesitate to open an issue, send a pull request, or reach out to me or @ngryman in any possible way!

reading-time v2

Here are a few changes we can make in v2 (most of which @ngryman has also mentioned), roughly in order of decreasing importance:

  1. Refactor the API to expose two separate functions;
  2. Remove text from the function return;
  3. Remove the badly named IOptions export;
  4. Migrate to TypeScript completely;
  5. Prefer ESM to CJS (once we have TypeScript this is just a matter of setting the transpilation target);
  6. Use a class-based implementation of readingTimeStream;
  7. Change the testing library from mocha to Jest.

@ngryman If you have limited availability, I can be here to help.

Reading time on one letter returns 'null'

There is a weird behaviour that causes reading-time to return null.

const t = require('reading-time');

t('OK'); // -> { time: ... }

// but
t('O'); // -> null

// whereas
t('😊'); // -> { time: ... } (certainly because it is a two bytes char)
t(''); // -> { time: ... }

So I am not sure why null is returned and if it should rather throw an exception or anything. But 'one letter' is definitely 'one word' and should consistently return an object.

An error (and not null) should rather be raised if the given input is not a string (not being able to be stringified β€” not sure we want to be able to try to get a result for { foo: 'bar' } argument).

An in-range update of mocha is breaking the build 🚨

Version 3.4.0 of mocha just got published.

Branch Build failing 🚨
Dependency mocha
Current Version 3.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v3.4.0

Mocha is now moving to a quicker release schedule: when non-breaking changes are merged, a release should happen that week.

This week's highlights:

  • allowUncaught added to commandline as --allow-uncaught (and bugfixed)
  • warning-related Node flags

πŸŽ‰ Enhancements

πŸ› Fixes

πŸ”© Other

Commits

The new version differs by 9 commits0.

  • 7554b31 Add Changelog for v3.4.0
  • 9f7f7ed Add --trace-warnings flag
  • 92561c8 Add --no-warnings flag
  • ceee976 lint test/integration/fixtures/simple-reporter.js
  • dcfc094 Revert "use semistandard directly"
  • 93392dd no special case for macOS running Karma locally
  • 4d1d91d --allow-uncaught cli option
  • fb1e083 fix allowUncaught in browser
  • 4ed3fc5 Add license report and scan status

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Breaking changes after patch update

We used to import 'reading-time' module as es6 module, now we get this error
Module '"reading-time"' resolves to a non-module entity and cannot be imported using this construct.

Also, the API provided minutes stat which is gone.

question on API

I'm considering making a VS Code extension using this library ... is this being actively updated?

Will the API be modified as per this issue? #18

Also, I noticed that the typescript typings file does not include the options argument.

Or do you recommend I fork this?

Change the API

Currently readingTime returns an object of the form:

{
  text: displayed + ' min read',
  minutes: minutes,
  time: time,
  words: words
}

That's too much and it's not easily composable. Let's decouple things and expose this API:

export const countWords = (text: string, options?: { bound?: string => boolean }): number
export const readingTime = (wordCount: number, options?: { wordsPerMinute?: number }): number
export default function(text, options) {
  return readingTime(countWords(text, options), options)
}

It would be nice to have .js (and min) file for vanilla JS projects

I'm working on a browser-based, vanilla, non-node project, and thus, I can't just do an npm install and go. Instead, I'm stuck including .js files via <script src=""> tags. It would be nice if you could provide .js files of the code -- perhaps minimized and un-minimized versions.

Generate a code playground

it would be nice to provide a code playground of this library, in order to test it with no effort & check if it suits the needs of those who want to use Reading-time lib

Suggestion: Japanese reading-time

Hi, I’m Japanese developer. Japanese is my native language.

If you have some time, please read this issue and respond any comments, suggestions, indicates

Premise

I already checked PR below.

#35

Background

I want to use this library for Japanese, but cannot use when I see https://github.com/ngryman/reading-time#help-wanted

I want to solve this problem !!

Main subject

In fact, calculation of Japanese reading-time is below.

reading-time [min] = charaters length / 600

ex: γ“γ‚“γ«γ‘γ―γ€γŠε…ƒζ°—γ§γ™γ‹οΌŸ
reading-time [min] = 13 / 600
γ€Œγ€γ€γ€Œγ€‚γ€γ€ŒοΌŸγ€γ€ŒοΌγ€is not pronounced, but pass time. So count 13 chars

So, if I can specify Japanese with some option, this library can calculate Japanese reading-time.

But, this library is used by mainly who uses English.

So, calculation is by word count.

If supply options to function like below, this library can count CJK languages,

type LangType = "en" | ... | "ja" | "cn" | "ko"
// cn = china, ko = korea
const stats = readingTime(text,lang="ja");

I’m not native of Chinese, Korean, so I don’t know about that truly.

By using Google, I can get a plausible value.

Additional

By using library below, we can count words.

https://github.com/leungwensen/tiny-segmenter

Streaming version

Hi there,

do you mind if I propose a PR which accepts a readableStream (and possibly works with Buffers rather than string conversion)?

Thanks :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.