Skip to content

Commit

Permalink
Add support for WHATWG URL
Browse files Browse the repository at this point in the history
Fixes: vfile#16
  • Loading branch information
aduh95 committed Jun 10, 2021
1 parent 243d8ea commit 7ed7ab3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
3 changes: 3 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import fs from 'fs'
import path from 'path'
import {fileURLToPath} from 'url'
import buffer from 'is-buffer'
import {VFile} from 'vfile'

Expand All @@ -35,6 +36,8 @@ import {VFile} from 'vfile'
export function toVFile(options) {
if (typeof options === 'string' || buffer(options)) {
options = {path: String(options)}
} else if (options && options.href && options.origin) {
options = {path: fileURLToPath(options)}
}

return options instanceof VFile ? options : new VFile(options)
Expand Down
9 changes: 5 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ npm install to-vfile
```js
import {toVFile} from 'to-vfile'

console.log(toVFile('readme.md'))
console.log(toVFile.readSync('.git/HEAD'))
console.log(toVFile.readSync('.git/HEAD', 'utf8'))
console.log(toVFile(new URL('./readme.md', import.meta.url)))
console.log(toVFile.readSync(new URL('./.git/HEAD', import.meta.url)))
console.log(toVFile.readSync(new URL('./.git/HEAD', import.meta.url), 'utf8'))
```
Yields:
Expand Down Expand Up @@ -67,7 +67,8 @@ There is no default export.
Create a virtual file.
Works like the [vfile][] constructor, except when `options` is `string` or
`Buffer`, in which case it’s treated as `{path: options}` instead of
`{value: options}`.
`{value: options}`, or when `options` is a WHATWG `URL` object, in which case
it’s treated as `{path: fileURLToPath(options)}`.
### `toVFile.read(options[, encoding][, callback])`
Expand Down
12 changes: 12 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,18 @@ test('toVFile()', function (t) {
st.equal(first, second)
st.end()
})

t.test('should accept a WHATWG URL object', function (st) {
var file = toVFile(new URL('file:///foo/bar/baz.qux'))

st.equal(file.path, join('/foo', 'bar', 'baz.qux'))
st.equal(file.basename, 'baz.qux')
st.equal(file.stem, 'baz')
st.equal(file.extname, '.qux')
st.equal(file.dirname, join('/foo', 'bar'))
st.equal(file.value, undefined)
st.end()
})
})

test('toVFile.readSync', function (t) {
Expand Down

0 comments on commit 7ed7ab3

Please sign in to comment.