What is file-url?
The file-url npm package is a utility that converts file paths to file URLs. This can be particularly useful when working with file systems in Node.js and needing to generate URLs that can be used in web contexts.
What are file-url's main functionalities?
Convert file path to file URL
This feature allows you to convert a given file path to a file URL. The resulting URL can be used in web contexts where a file URL is required.
const fileUrl = require('file-url');
const url = fileUrl('/path/to/file');
console.log(url); // Outputs: 'file:///path/to/file'
Convert file path to file URL with custom options
This feature allows you to convert a file path to a file URL with additional options. For example, the 'resolve' option can be used to resolve the file path to an absolute path before converting it to a URL.
const fileUrl = require('file-url');
const url = fileUrl('/path/to/file', { resolve: true });
console.log(url); // Outputs: 'file:///absolute/path/to/file'
Other packages similar to file-url
url
The url package is a core Node.js module that provides utilities for URL resolution and parsing. While it is more general-purpose and not specifically focused on file URLs, it can be used to achieve similar results with more manual effort.
file-uri-to-path
The file-uri-to-path package does the reverse of file-url by converting file URLs back to file paths. It can be used in conjunction with file-url for bidirectional conversions between file paths and URLs.
file-url
Convert a file path to a file url: unicorn.jpg
→ file:///Users/sindresorhus/unicorn.jpg
Install
$ npm install file-url
Usage
import fileUrl from 'file-url';
fileUrl('unicorn.jpg');
fileUrl('/Users/pony/pics/unicorn.jpg');
fileUrl('unicorn.jpg', {resolve: false});
API
fileUrl(filePath, options?)
Returns the filePath
converted to a file URL.
filePath
Type: string
File path to convert.
options
Type: object
resolve
Type: boolean
Default: true
Passing false
will make it not call path.resolve()
on the path.
Related