Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/webtorrent/webtorrent.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md19
-rw-r--r--lib/storage.js24
2 files changed, 35 insertions, 8 deletions
diff --git a/README.md b/README.md
index 7c5a1d2..b9ac698 100644
--- a/README.md
+++ b/README.md
@@ -428,13 +428,28 @@ You can pass `opts` to stream only a slice of a file.
Both `start` and `end` are inclusive.
+#### `file.getBuffer(function callback (err, url) {})`
+
+Get the file contents as a `Buffer`.
+
+The file will be fetched from the network with highest priority, and `callback` will be
+called once the file is ready. `callback` must be specified, and will be called with a an
+`Error` (or `null`) and the file contents as a `Buffer`.
+
+```js
+file.getBuffer(function (err, buffer) {
+ if (err) throw err
+ console.log(buffer) // <Buffer 00 98 00 01 01 00 00 00 50 ae 07 04 01 00 00 00 0a 00 00 00 00 00 00 00 78 ae 07 04 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ...>
+})
+```
+
#### `file.getBlobURL(function callback (err, url) {})`
Get a url which can be used in the browser to refer to the file.
The file will be fetched from the network with highest priority, and `callback` will be
-called when it is ready. `callback` must be specified and may be called with a an `Error`
-or the blob url (`String`) when the file data is available and ready to be used.
+called once the file is ready. `callback` must be specified, and will be called with a an
+`Error` (or `null`) and the Blob URL (`String`).
```js
file.getBlobURL(function (err, url) {
diff --git a/lib/storage.js b/lib/storage.js
index 5454a38..d652c66 100644
--- a/lib/storage.js
+++ b/lib/storage.js
@@ -254,20 +254,32 @@ File.prototype.createReadStream = function (opts) {
}
/**
- * TODO: detect errors and call callback with error
* @param {function} cb
*/
File.prototype.getBlobURL = function (cb) {
var self = this
- var chunks = []
+ self.getBuffer(function (err, buf) {
+ if (err) return cb(err)
+ var url = URL.createObjectURL(new Blob([ buf ]))
+ cb(null, url)
+ })
+}
+
+/**
+ * TODO: detect errors and call callback with error
+ * @param {function} cb
+ */
+File.prototype.getBuffer = function (cb) {
+ var self = this
+ var buf = new Buffer(self.length)
+ var start = 0
self.createReadStream()
.on('data', function (chunk) {
- chunks.push(chunk)
+ chunk.copy(buf, start)
+ start += chunk.length
})
.on('end', function () {
- var buf = Buffer.concat(chunks)
- var url = URL.createObjectURL(new Blob([ buf ]))
- cb(null, url)
+ cb(null, buf)
})
}