diff --git a/lib/index.js b/lib/index.js index 0f93eb9..2f38f10 100644 --- a/lib/index.js +++ b/lib/index.js @@ -8,7 +8,8 @@ * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, mode: Mode?, flag?: string}} WriteOptions * * @typedef {string|Uint8Array} Path Path of the file. - * @typedef {Path|Options|VFile} Compatible Things that can be + * @typedef {typeof import('url').URL} URL WHATWG URL + * @typedef {Path|URL|Options|VFile} Compatible Things that can be * passed to the function. */ @@ -20,6 +21,7 @@ import fs from 'fs' import path from 'path' +import {fileURLToPath} from 'url' import buffer from 'is-buffer' import {VFile} from 'vfile' @@ -35,6 +37,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) diff --git a/readme.md b/readme.md index 98d0962..c101c8b 100644 --- a/readme.md +++ b/readme.md @@ -28,6 +28,7 @@ npm install to-vfile import {toVFile} from 'to-vfile' console.log(toVFile('readme.md')) +console.log(toVFile(new URL('./readme.md', import.meta.url))) console.log(toVFile.readSync('.git/HEAD')) console.log(toVFile.readSync('.git/HEAD', 'utf8')) ``` @@ -41,6 +42,12 @@ VFile { history: ['readme.md'], cwd: '/Users/tilde/projects/oss/to-vfile' } +VFile { + data: {}, + messages: [], + history: ['readme.md'], + cwd: '/Users/tilde/projects/oss/to-vfile' +} VFile { data: {}, messages: [], @@ -67,7 +74,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])` diff --git a/test.js b/test.js index 61b8588..2cdefd9 100644 --- a/test.js +++ b/test.js @@ -1,5 +1,6 @@ import fs from 'fs' import path from 'path' +import {fileURLToPath, URL} from 'url' import test from 'tape' import buffer from 'is-buffer' import {toVFile} from './index.js' @@ -52,6 +53,19 @@ test('toVFile()', function (t) { st.equal(first, second) st.end() }) + + t.test('should accept a WHATWG URL object', function (st) { + const dir = fileURLToPath(new URL('./', import.meta.url)) + var file = toVFile(new URL('./baz.qux', import.meta.url)) + + st.equal(file.path, join(dir, 'baz.qux')) + st.equal(file.basename, 'baz.qux') + st.equal(file.stem, 'baz') + st.equal(file.extname, '.qux') + st.equal(file.dirname, dir.replace(/[/\\]$/, '')) + st.equal(file.value, undefined) + st.end() + }) }) test('toVFile.readSync', function (t) {