• Stars
    star
    148
  • Rank 249,983 (Top 5 %)
  • Language
    TypeScript
  • License
    Other
  • Created almost 11 years ago
  • Updated 26 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Determine if a filename and/or buffer is text or binary. Smarter detection than the other solutions.

Is Text or Binary?

Status of the GitHub Workflow: bevry NPM version NPM downloads Dependency Status Dev Dependency Status
GitHub Sponsors donate button Patreon donate button Flattr donate button Liberapay donate button Buy Me A Coffee donate button Open Collective donate button crypto donate button PayPal donate button Wishlist browse button

Determine if a filename and/or buffer is text or binary. Smarter detection than the other solutions.

Determination works like so:

  1. Extension Check: If filename is available, check if any of its extensions (from right to left) are an text extension or a binary extension, this is near instant.
  2. Contents Check: If no filename was provided, or the extension check was indeterminate, then check the contents of the buffer.

The extension check will check each of the filename's extensions, from right to left. This is done as certain applications utilise multiple extensions for transformations, such as app.x.y may tell a compiler to transform from x format to y format, in this case perhaps x is not a recognized extension but y is, in which case we can make use of that to provide superior accuracy and convenience compared to just checking the rightmost extension.

The contents check (with the default options) will check 24 bytes at the start, middle, and end of the buffer. History has shown that checking all three locations is mandatory for accuracy, and that anything less is not accurate. This technique offers superior performance while still offering superior accuracy. Alternatives generally just do 1000 bytes at the start, which is slower, and inaccurate.

One cannot just do the contents check alone because UTF16 characters are indistinguishable from binary which would return an inaccurate result, hence why the combination is necessary for accuracy, with performance for known extensions a side-effect.

As such, this library's combination of extension check (if filename is provided), then contents check (if buffer is provided), offers superior performance and accuracy to alternatives.

Ever since 2012, this module's superior accuracy and performance has been essential to the operation of DocPad and its other dependents.

Usage

Complete API Documentation.

import { isText, isBinary, getEncoding } from 'istextorbinary'

or

const { isText, isBinary, getEncoding } = require('istextorbinary')

then

isText(aFilename) // returns true if a text file otherwise false, checks only filename
isText(null, aBuffer) // returns true if a text file otherwise false, checks only buffer
isText(aFilename, aBuffer) // returns true if a text file otherwise false, checks filename then buffer
isText(null, null) // returns null

isBinary(aFilename) // returns true if a binary file otherwise false, checks only filename
isBinary(null, aBuffer) // returns true if a binary file otherwise false, checks only buffer
isBinary(aFilename, aBuffer) // returns true if a binary file otherwise false, checks filename then buffer
isBinary(null, null) // returns null

getEncoding(aBuffer) // returns 'binary' if it contained non-utf8 characters, otherwise returns 'utf8'

Install

npm

  • Install: npm install --save istextorbinary
  • Import: import * as pkg from ('istextorbinary')
  • Require: const pkg = require('istextorbinary')

Skypack

<script type="module">
    import * as pkg from '//cdn.skypack.dev/istextorbinary@^6.0.0'
</script>

unpkg

<script type="module">
    import * as pkg from '//unpkg.com/istextorbinary@^6.0.0'
</script>

jspm

<script type="module">
    import * as pkg from '//dev.jspm.io/[email protected]'
</script>

Editions

This package is published with the following editions:

  • istextorbinary/source/index.ts is TypeScript source code with Import for modules
  • istextorbinary/edition-browsers/index.js is TypeScript compiled against ES2020 for web browsers with Import for modules
  • istextorbinary aliases istextorbinary/edition-es2019/index.js
  • istextorbinary/edition-es2019/index.js is TypeScript compiled against ES2019 for Node.js 10 || 12 || 14 || 16 with Require for modules
  • istextorbinary/edition-es2019-esm/index.js is TypeScript compiled against ES2019 for Node.js 12 || 14 || 16 with Import for modules

History

Discover the release history by heading on over to the HISTORY.md file.

Contribute

Discover how you can contribute by heading on over to the CONTRIBUTING.md file.

Backers

Maintainers

These amazing people are maintaining this project:

Sponsors

No sponsors yet! Will you be the first?

GitHub Sponsors donate button Patreon donate button Flattr donate button Liberapay donate button Buy Me A Coffee donate button Open Collective donate button crypto donate button PayPal donate button Wishlist browse button

Contributors

These amazing people have contributed code to this project:

Discover how you can contribute by heading on over to the CONTRIBUTING.md file.

License

Unless stated otherwise all works are:

and licensed under:

More Repositories

1

cson

CoffeeScript-Object-Notation. Same as JSON but for CoffeeScript objects.
CoffeeScript
1,340
star
2

watchr

Better file system watching for Node.js. Provides a normalised API the file watching APIs of different node versions, nested/recursive file and directory watching, and accurate detailed events for file/directory changes, deletions and creations.
JavaScript
538
star
3

caterpillar

Caterpillar is the ultimate logging system for Deno, Node.js, and Web Browsers. Log levels are implemented to the RFC standard. Log entries can be filtered and piped to various streams, including coloured output to the terminal, the browser's console, and debug files. You can even write your own transforms.
TypeScript
402
star
4

staticsitegenerators-website

Website containing the complete listing of static site generators
TypeScript
364
star
5

getmac

Get the mac address of the current machine you are on via Node.js
TypeScript
358
star
6

query-engine

QueryEngine provides extensive Querying, Filtering, and Searching abilities for Backbone.js Collections as well as JavaScript arrays and objects
CoffeeScript
328
star
7

dorothy

🧙🏻‍♀️ Bring your dotfile commands and configuration to any shell. Sensible defaults and hundreds of commands preloaded. Supports Bash, Zsh, Fish, Nu, Xonsh, Elvish, Dash, KornShell, macOS, Linux, Windows.
Shell
321
star
8

projectz

Stop wasting time maintaining your project's readme and package files! Let Projectz do it for you.
TypeScript
266
star
9

staticsitegenerators-list

A comprehensive, partially automatically generated comparison of static site generators
TypeScript
221
star
10

badges

The definitive rendering collection of badges
TypeScript
114
star
11

envfile

Parse and write environment files with Node.js
TypeScript
61
star
12

editions

📦 The best way to produce and consume the JavaScript packages you care about.
TypeScript
61
star
13

typechecker

Utilities to get and check variable types (isString, isPlainObject, isRegExp, etc)
TypeScript
49
star
14

taskgroup

Group together synchronous and asynchronous tasks and execute them with support for concurrency, naming, and nesting.
JavaScript
49
star
15

make-deno-edition

Automatically makes package.json projects (such as npm packages and node.js modules) compatible with Deno.
TypeScript
43
star
16

kava

Kava has been powering accurate test suites in node.js and the browser since 2012.
JavaScript
33
star
17

domain-browser

Node's domain module for the web browser
JavaScript
31
star
18

base

Base files for new projects
30
star
19

terraform-scaleway-hashistack

Terraform module to deploy Consul, Nomad, Vault onto Scaleway
Shell
20
star
20

boundation

Automatic scaffolding and upgrading of your JavaScript ecosystem projects using Bevry's best practices
JavaScript
19
star
21

safeps

Work with processes safely and easily in Node.js
JavaScript
17
star
22

filedirname

Fetch the current file and directory path, no matter your environment (Deno, Node.js, Web Browsers, ESM, CJS)
TypeScript
16
star
23

get-current-line

Get the current line number of the executing file and method
TypeScript
15
star
24

ambi

Ambi lets you execute any function ambidextrously; providing you the ability to execute any function (be it synchronous, asynchronous, returns, callbacks, promises) as if it returned a promise.
TypeScript
15
star
25

textextensions

The definitive listing of filename extensions that are used for text files.
TypeScript
13
star
26

coda-packs

Monorepo of Coda packs
TypeScript
12
star
27

daet

Minimal immutable date class that supports relative time, calendar time, and plus/minus of different units.
TypeScript
11
star
28

errlop

An extended Error class that envelops a parent error, such that the stack trace contains the causation
TypeScript
9
star
29

native-promise-pool

Create a pool of a specified concurrency that accepts promises
TypeScript
9
star
30

pluginclerk

 A clerk for retrieving compatible plugins from the npm database
TypeScript
9
star
31

event-emitter-grouped

Emit events in serial or parallel with support for synchronous and asynchronous listeners
JavaScript
9
star
32

awesome-crypto

The definitive listing of every cryptocurrency service; including their capabilities, fees, currencies, withdrawal process, etc.
9
star
33

extract-opts

Deprecated. Convert your API to promises
JavaScript
7
star
34

getsetdeep

Get or set nested variables of an object
TypeScript
7
star
35

sortobject

Deeply sort an object by its keys without mangling any arrays inside of it
TypeScript
7
star
36

scandirectory

Scan a directory recursively with a lot of control and power
TypeScript
7
star
37

safefs

Deprecated. Use the @bevry/fs-* packages instead
JavaScript
7
star
38

discourser

Discourse API Client written in TypeScript for Node.js and Browser environments
TypeScript
6
star
39

meetings

Bevry Meetings Website (WIP)
TypeScript
6
star
40

eachr

Deprecated: Use `for ( const [key, value] of Object.entries(thing) )`
TypeScript
6
star
41

binaryextensions

The definitive listing of filename extensions that are used for binary files.
TypeScript
6
star
42

arrangekeys

Returns a copy of a JavaScript object with the keys arranged in a specified order. Useful for formatting JSON files.
TypeScript
6
star
43

extendr

Utilities for cloning, extending, and de-referencing objects in shallow, deep, and safe ways
JavaScript
5
star
44

hooks

Aggregation of react hooks that we use. Such as useInterval and useMetaKey.
TypeScript
5
star
45

get-cli-arg

Deprecated. Use https://github.com/bevry/argument
TypeScript
5
star
46

cachely

A tiny wrapper that sits around your request function that caches its data for a specified duration, provides updates as requested rather than polling each interval
TypeScript
5
star
47

ropo

String replacement utilities with support for both synchronous and asynchronous replacements. Supports replacing Regular Expressions, HTML Elements, and Comment Elements. Compatible with async/await.
TypeScript
5
star
48

eslint-config-bevry

Bevry's ESLint configuration is an adaptive configuration that automatically configures ESLint
JavaScript
4
star
49

ansi

ANSI colors and styles for Deno, Node.js, JavaScript, and TypeScript
TypeScript
4
star
50

billing

Bevry's billing system
TypeScript
4
star
51

pluginloader

A class for loading, verifying, and creating plugins. Used by DocPad for years.
TypeScript
4
star
52

oneday

The number of milliseconds in one day
TypeScript
3
star
53

github-api

Interact with the GitHub API, fetching commits, repositories, members, and backers (authors, maintainers, contributors, funders, sponsors, donors)
TypeScript
3
star
54

start-of-week

Returns the start of the week based on the locale.
TypeScript
3
star
55

memo

Wrap a function in a memo to reuse the first invocation result of the function
TypeScript
3
star
56

progress-title

Your usual progress bar, but this time it is displayed within the terminal's title, which is much simpler
JavaScript
3
star
57

list

List/array/set utility functions: union, intersect, complement, unique, first, last, has, add, toggle
TypeScript
3
star
58

hostenv

Exports the correct PORT and HOSTNAME values for Heroku, AppFog, CloudFoundry, OpenShift, and other service environments
TypeScript
2
star
59

arrange-package-json

Arrange the properties in the package.json file to a universally consistent order
TypeScript
2
star
60

github-orgs

JSON listing of all the Bevry managed GitHub organisations
TypeScript
2
star
61

trim-indentation

Trim the initial indentation from a string
TypeScript
2
star
62

version-range

Check version ranges like `>=N` and `X || Y || Z` with support for Node.js, Web Browsers, Deno, and TypeScript.
TypeScript
2
star
63

docmatter

Battle tested SSG front matter parser. Extracted from DocPad. Delimiter lines have 3+ of the same character (such as /*** and ***/) allowing front matters to work with the syntax highlighting of your code editor. Supports custom parsers, e.g. --- cson. Parsers are handled externally.
CoffeeScript
2
star
64

mdx

MDX loader for Next.js
TypeScript
2
star
65

discourse-component-youtubetimestamps

Convert timetamps in your post, to a timestamped link to the post's (otherwise topic's) referenced youtube video
HTML
2
star
66

json

Helpers for reading and writing JSON.
TypeScript
2
star
67

designs

Designs and resources for our company, community, and products
2
star
68

version-compare

Compare two versions quickly
TypeScript
2
star
69

dominject

Inject scripts and styles into the DOM with duplicate prevention and completion callback support
JavaScript
2
star
70

normalify

Normalize different variable value types - e.g. `"1"` becomes `1`
TypeScript
2
star
71

nodejs-versions

Filter the absolute or significant Node.js versions by vast amounts of criteria, such as LTS status.
TypeScript
2
star
72

fs-accessible

Check if a path is accessible
TypeScript
1
star
73

requirefresh

Require a file without adding it into the require cache
TypeScript
1
star
74

logger-clearable

A logger that is clearable
JavaScript
1
star
75

valid-directory

Check whether or not the current working directory is valid on windows
TypeScript
1
star
76

valid-filename

Check if a string is a valid filename.
TypeScript
1
star
77

assert-helpers

Common utilities and helpers to make testing assertions easier
TypeScript
1
star
78

rfc-log-levels

A map of log level aliases matched to their numeric values. Follows the RFC Standard.
TypeScript
1
star
79

.github

1
star
80

duration-timestamp

Parse and stringify duration timestamps (such as hh:mm:ss and HhMmSs)
TypeScript
1
star
81

detect-indentation

Utility to detect indentation from a string
TypeScript
1
star
82

render

Render elements for HTML and Markdown
TypeScript
1
star
83

valid-module

Verify that file or package, be it remote, or local, is a valid ECMAScript Module
TypeScript
1
star
84

file-url-to-path

Convert a file: URL to its path
TypeScript
1
star
85

fellow

Fellow is a package for creating people that can be unified by their shared values via a singleton list on the class
TypeScript
1
star
86

unicode-symbols

Unicode Symbols
TypeScript
1
star
87

links

Collection of Links for Redirection on the Bevry websites
TypeScript
1
star
88

ignorepatterns

A regular expression that matches common filenames that we want to ignore
TypeScript
1
star
89

spinner-title

Write your spinner to the terminal title bar
TypeScript
1
star
90

ignorefs

Ignore common and custom patterns of the file system
TypeScript
1
star
91

ecmascript-versions

Get all ECMAScript versions, or the ECMAScript version that was ratified on a specific date.
TypeScript
1
star
92

unbounded

Function.prototype.bind replacement that provides an `unbounded` hidden property on the returned bounded function, that contains the original unbounded function
TypeScript
1
star
93

version-clean

Turn a dirty version (such as v1, =1.0.x, >1.0 <2) into a clean version (1.0)
TypeScript
1
star