From 7ed7ab3f87a89663cc7547cd3a745e5f62b52899 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Thu, 10 Jun 2021 15:27:22 +0200 Subject: [PATCH] Add support for WHATWG URL Fixes: https://github.com/vfile/to-vfile/issues/16 --- lib/index.js | 3 +++ readme.md | 9 +++++---- test.js | 12 ++++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index 0f93eb9..f0bee94 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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' @@ -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) diff --git a/readme.md b/readme.md index 98d0962..9ccdfb7 100644 --- a/readme.md +++ b/readme.md @@ -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: @@ -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])` diff --git a/test.js b/test.js index 61b8588..ea0afb9 100644 --- a/test.js +++ b/test.js @@ -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) {