1 | # isBinaryFile
|
2 |
|
3 | Detects 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 |
|
8 | Much of the logic is pretty much ported from [ag](https://github.com/ggreer/the_silver_searcher).
|
9 |
|
10 | Note: if the file doesn't exist or is a directory, an error is thrown.
|
11 |
|
12 | ## Installation
|
13 |
|
14 | ```
|
15 | npm install isbinaryfile
|
16 | ```
|
17 |
|
18 | ## Usage
|
19 |
|
20 | Returns `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 |
|
43 | Here's an arbitrary usage:
|
44 |
|
45 | ```javascript
|
46 | const isBinaryFile = require("isbinaryfile").isBinaryFile;
|
47 | const fs = require("fs");
|
48 |
|
49 | const filename = "fixtures/pdf.pdf";
|
50 | const data = fs.readFileSync(filename);
|
51 | const stat = fs.lstatSync(filename);
|
52 |
|
53 | isBinaryFile(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 |
|
62 | const isBinaryFileSync = require("isbinaryfile").isBinaryFileSync;
|
63 | const bytes = fs.readFileSync(filename);
|
64 | const size = fs.lstatSync(filename).size;
|
65 | console.log(isBinaryFileSync(bytes, size)); // true or false
|
66 | ```
|
67 |
|
68 | ## Testing
|
69 |
|
70 | Run `npm install`, then run `npm test`.
|