Fast, easy and dynamic tokenizer for Node Streams
It was originally inspired by node-tokenizer, but quickly grew into its own form as I wanted it to be RegExp agnostic so it could be used on node Buffer intances and more importantly faster. As of the first release, it does not support Buffer instances (yet!) but it is planned to be the next major feature.
It is published on node package manager (npm). To install, do:
npm install atok
Given the following json to be parsed:
The following code would be a very simple JSON parser for it.
var Tokenizer = require'..'var tok =// Define the parser rules// By default it will emit data events when a rule is matchedtok// Define the quiet property for the following rules (quiet=dont tokenize but emit/trigger the handler)// Only used to improve performancequiettrue// first argument is a match on the current position in the bufferaddRule'[' 'array-start'addRule']' 'array-end'quiet // Turn the quiet property off// The second pattern will only match if it is not escaped (default escape character=\)escapedtrueaddRule'"' '"' 'string'escaped// Array item separatoraddRule',' 'separator'// Skip the match, in this case whitespacesignoretrueaddRule' ''\n' '\t''\r' 'whitespaces'ignore// End of the buffer reached// This is usually only needed when implementing synchronous parsersaddRule0 'end'// Setup some variablesvar stack =var inArray = false// Attach listeners to the tokenizertokon'data'// token=the matched data// idx=when using array of patterns, the index of the matched pattern// type=string identifiers used in the rule definitionswitch typecase 'array-start':stackpushinArray = truebreakcase 'array-end':inArray = falsebreakcase 'string':if inArraystack stacklength-1 pushtokenelsethrow 'only Arrays supported'breakcase 'separator':breakcase 'end':console.log'results is of type' typeof stack0 'with' stack0length 'item(s)'console.log'results:' stack0stack =breakdefault:throw 'Unknown type: ' + type// Send some data to be parsed!tokwrite'[ "Hello", "world!" ]'
results is object with 1 item(s) results: [ 'Hello world!' ]
Atok performance was tested by writing a JSON parser and comparing its results to the excellent Douglas Crockford's . It currently scores slower on data sets containing small items, but much faster on large ones.
The JSON parser based on atok will be published soon as well as the benchmarks for it.
There are plans to increase performance, as listed in the TODO document.