Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add file.getBuffer() API #230

Merged
merged 4 commits into from Jan 4, 2015
Merged
Changes from 1 commit
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

Next

Add file.getBuffer() API

  • Loading branch information
feross committed Jan 4, 2015
commit 8fd9cb092ae5899767c1ae7bab2be872c9543e35
@@ -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) {
@@ -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)
})
}

ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.