| 1 |
# Split (matcher) |
| 2 |
|
| 3 |
[](http://travis-ci.org/dominictarr/split) |
| 4 |
|
| 5 |
Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp` |
| 6 |
|
| 7 |
Example, read every line in a file ... |
| 8 |
|
| 9 |
``` js |
| 10 |
fs.createReadStream(file) |
| 11 |
.pipe(split()) |
| 12 |
.on('data', function (line) { |
| 13 |
//each chunk now is a separate line! |
| 14 |
}) |
| 15 |
|
| 16 |
``` |
| 17 |
|
| 18 |
`split` takes the same arguments as `string.split` except it defaults to '/\r?\n/' instead of ',', and the optional `limit` parameter is ignored. |
| 19 |
[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) |
| 20 |
|
| 21 |
`split` takes an optional options object on its third argument. |
| 22 |
|
| 23 |
``` js |
| 24 |
split(matcher, mapper, options) |
| 25 |
``` |
| 26 |
|
| 27 |
Valid options: |
| 28 |
|
| 29 |
* maxLength - The maximum buffer length without seeing a newline or `matcher`, |
| 30 |
if a single line exceeds this, the split stream will emit an error. |
| 31 |
|
| 32 |
``` js |
| 33 |
split(JSON.parse, null, { maxLength: 2}) |
| 34 |
``` |
| 35 |
|
| 36 |
* trailing - By default the last buffer not delimited by a newline or `matcher` will be emitted. To prevent this set `options.trailing` to `false`. |
| 37 |
|
| 38 |
``` js |
| 39 |
split(JSON.parse, null, { trailing: false }) |
| 40 |
``` |
| 41 |
|
| 42 |
## keep matched splitter |
| 43 |
|
| 44 |
As with `String#split`, if you split by a regular expression with a matching group, |
| 45 |
the matches will be retained in the collection. |
| 46 |
|
| 47 |
``` |
| 48 |
stdin |
| 49 |
.pipe(split(/(\r?\n)/)) |
| 50 |
... //lines + separators. |
| 51 |
``` |
| 52 |
|
| 53 |
|
| 54 |
# NDJ - Newline Delimited Json |
| 55 |
|
| 56 |
`split` accepts a function which transforms each line. |
| 57 |
|
| 58 |
``` js |
| 59 |
fs.createReadStream(file) |
| 60 |
.pipe(split(JSON.parse)) |
| 61 |
.on('data', function (obj) { |
| 62 |
//each chunk now is a a js object |
| 63 |
}) |
| 64 |
.on('error', function (err) { |
| 65 |
//syntax errors will land here |
| 66 |
//note, this ends the stream. |
| 67 |
}) |
| 68 |
``` |
| 69 |
|
| 70 |
# License |
| 71 |
|
| 72 |
MIT |