-
Notifications
You must be signed in to change notification settings - Fork 57
Loading and saving data
In most cases you don't have binary data hard-coded in your JavaScript (why do you need any operation on it otherwise, eh?).
So you need to get this data from some external source and show result when you are done.
And jBinary
provides handy methods for that:
-
jBinary.loadData(source, [callback])
(static method):Loads data from given
source
and returns it inPromise
or Node.js-likecallback(error, data)
if specified.Source can be one of (if supported on current engine):
- Blob / File instance (HTML5 File API).
- HTTP(S) URL (should be on the same host or allowed by CORS if called from browser).
- Data-URI (simple or base64-encoded).
- Node.js local file path.
- Node.js Readable stream.
-
jBinary.load(source, [typeSet], [callback])
(static method):
Loads data from given source
using jBinary.loadData
, detects typeset using Repo associations if it's not specified explicitly, creates jBinary
instance on this data and typeset and returns it in Promise
or Node.js-like callback(error, data)
if specified.
If Repo is not used, jBinary.load
would accept only explicit typeset objects (no loading by name nor file format auto-detection).
saveAs(dest, mimeType = 'application/octet-stream', [callback])
Saves data to given destination and returns Promise
or calls Node.js-like callback(error, data)
if specified.
mimeType
is set from given argument, typeSet['jBinary.mimeType']
directive or default to 'application/octet-stream'
in order of precedence.
Destination can be one of (if supported on current engine):
* File name to be used in browser "Save as" dialog (is shown to end user; old browsers might not use custom filename).
* Node.js local file path.
* Node.js [Writable stream](http://nodejs.org/api/stream.html#stream_class_stream_writable).
toURI(mimeType = 'application/octet-stream')
Returns URI suitable for usage in DOM elements (uses Blob
URIs where supported, data-URIs in other cases, so may be problematic when creating from big data in old browsers).
fileInput.addEventListener('change', function () {
jBinary.loadData(fileInput.files[0]).then(function (data) {
if (error) {
return console.log(error);
}
// here you get data from <input type="file" /> that you can use in jDataView/jBinary constructors
});
});
jBinary.load('sample.tar').then(function (binary) {
// here TAR format is auto-detected and used by `binary` (in the case you use it in combination with jBinary.Repo; if not, jBinary with default typeset will be used)
var tar = binary.read('File');
// ... more code ...
return binary.saveAs('new.tar'); // opens browser's "Save as" dialog or saves to disk if called from Node.js
}).then(function () {
console.log('Processed and saved successfully!');
}, function (err) {
console.error(err);
});