Open shawnbot opened 8 years ago
This might be all that the tito
CLI really needs to do:
var subarg = require('subarg');
var argv = subarg(process.argv.slice(2));
var input = qualify(argv._[0], '/dev/stdin', argv.read || {});
var output = qualify(argv._[1], '/dev/stdout', argv.write || {});
var tito = require('tito');
var read = tito.createReadStream(input.filename, input.format, input.options);
var write = tito.createWriteStream(output.filename, output.format, output.options);
read.pipe(write);
function qualify(filename, fallback, options) {
var format = 'ndjson';
if (!filename || filename === '-') {
filename = fallback;
} else if (filename.indexOf('.') > -1) {
format = filename.substr(filename.lastIndexOf('.') + 1);
}
if (options._[0]) {
format = options._[0];
}
return {
filename: filename,
format: format,
options: options
};
}
JS API
Open and parse a file in a known format
This is the equivalent of:
Open and write to a file in a known format
i.e.
Format inference
If no
format
is provided it should be inferred from the filename (filename.split('.').pop()
); an error would be thrown if no extension is found.File-agnostic streams
Under the hood, the read and write stream functions would use the following to create parse and format streams:
to parse strings into objects (e.g. CSV to JSON), and
to go the other way (JSON to CSV).
Format resolution
If the parse or format stream functions can't resolve the
format
argument, then they will look for a module by the same name with two top-level functions:format.createReadStream([options])
andformat.createWriteStream([options])
, respectively. This allows "pluggable" formats and makes wrapping existing APIs much simpler. (There should also be a simple way to specify per-format option name mappings so that you can use, say,-d
as a shorthand for--delimiter
.)CLI
The
tito
command line interface is wonky. Here is a better way to do it.It should infer formats from positional arguments in the form:
(If no output filename is provided, use stdout. If no input filename is provided, use stdin. The value
-
can be used to represent either, respectively.)It should use subarg or similar to parse options for the read and/or write formats:
Examples