UNPKG

1.89 kBMarkdownView Raw
1# isBinaryFile
2
3Detects if a file is binary in Node.js using ✨promises✨. Similar to [Perl's `-B` switch](http://stackoverflow.com/questions/899206/how-does-perl-know-a-file-is-binary), in that:
4- it reads the first few thousand bytes of a file
5- checks for a `null` byte; if it's found, it's binary
6- flags non-ASCII characters. After a certain number of "weird" characters, the file is flagged as binary
7
8Much of the logic is pretty much ported from [ag](https://github.com/ggreer/the_silver_searcher).
9
10Note: if the file doesn't exist or is a directory, an error is thrown.
11
12## Installation
13
14```
15npm install isbinaryfile
16```
17
18## Usage
19
20Returns `Promise<boolean>` (or just `boolean` for `*Sync`). `true` if the file is binary, `false` otherwise.
21
22### isBinaryFile(filepath)
23
24* `filepath` - a `string` indicating the path to the file.
25
26### isBinaryFile(bytes[, size])
27
28* `bytes` - a `Buffer` of the file's contents.
29* `size` - an optional `number` indicating the file size.
30
31### isBinaryFileSync(filepath)
32
33* `filepath` - a `string` indicating the path to the file.
34
35
36### isBinaryFileSync(bytes[, size])
37
38* `bytes` - a `Buffer` of the file's contents.
39* `size` - an optional `number` indicating the file size.
40
41### Examples
42
43Here's an arbitrary usage:
44
45```javascript
46const isBinaryFile = require("isbinaryfile").isBinaryFile;
47const fs = require("fs");
48
49const filename = "fixtures/pdf.pdf";
50const data = fs.readFileSync(filename);
51const stat = fs.lstatSync(filename);
52
53isBinaryFile(data, stat.size).then((result) => {
54 if (result) {
55 console.log("It is binary!")
56 }
57 else {
58 console.log("No it is not.")
59 }
60});
61
62const isBinaryFileSync = require("isbinaryfile").isBinaryFileSync;
63const bytes = fs.readFileSync(filename);
64const size = fs.lstatSync(filename).size;
65console.log(isBinaryFileSync(bytes, size)); // true or false
66```
67
68## Testing
69
70Run `npm install`, then run `npm test`.