我有本地文件路径(在node.js中),我需要将它们转换为file://
URL.
我现在正在查看https://en.wikipedia.org/wiki/File_URI_scheme,我觉得这必须是一个已解决的问题,并且有人必须有一个片段或npm模块来执行此操作.
但后来我尝试搜索npm这个,但是我得到了太多的瑕疵,这是不好笑的(文件,网址和路径是像所有包中的搜索命中:)与谷歌和SO相同.
我可以做这种天真的做法
site = path.resolve(site); if (path.sep === '\\') { site = site.split(path.sep).join('/'); } if (!/^file:\/\//g.test(site)) { site = 'file:///' + site; }
但我很确定这不是要走的路.
使用该file-url
模块.
npm install --save file-url
用法:
var fileUrl = require('file-url'); fileUrl('unicorn.jpg'); //=> file:///Users/sindresorhus/dev/file-url/unicorn.jpg fileUrl('/Users/pony/pics/unicorn.jpg'); //=> file:///Users/pony/pics/unicorn.jpg
也适用于Windows.并且代码很简单,以防你想要一个片段:
var path = require('path'); function fileUrl(str) { if (typeof str !== 'string') { throw new Error('Expected a string'); } var pathName = path.resolve(str).replace(/\\/g, '/'); // Windows drive letter must be prefixed with a slash if (pathName[0] !== '/') { pathName = '/' + pathName; } return encodeURI('file://' + pathName); };
Node.js v10.12.0仅提供了两种新方法来解决此问题:
const url = require('url'); url.fileURLToPath(url) url.pathToFileURL(path)
https://nodejs.org/api/url.html#url_url_pathtofileurl_path
https://nodejs.org/api/url.html#url_url_fileurltopath_url