我有本地文件路径(在node.js中),我需要将它们转换为file:// urls。
我现在正在研究https://en.wikipedia.org/wiki/File_URI_scheme,我觉得这肯定是一个已经解决的问题,必须有人有一个代码片段或npm模块来做这件事。
但是后来我试着在npm上搜索这个,但我得到了太多的麻烦,这并不好笑(文件,url和路径是搜索命中的,就像每个包一样:) google也是如此。
我可以用这种天真的方法
site = path.resolve(site);
if (path.sep === '\\') {
site = site.split(path.sep).join('/');
}
if (!/^file:\/\//g.test(site)) {
site = 'file:///' + site;
}但我很确定这不是一条正确的道路。
发布于 2015-01-29 20:14:32
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);
};发布于 2018-12-14 23:52:38
Node.js v10.12.0提供了两种新的方法来解决这个问题:
const url = require('url');
url.fileURLToPath(url)
url.pathToFileURL(path)文档
发布于 2018-04-17 02:41:15
我有一个类似的issue,但最终解决方案是使用新的WHATWG URL实现:
const path = 'c:\\Users\\myname\\test.swf';
const u = new URL(`file:///${path}`).href;
// u = 'file:///c:/Users/myname/test.swf'https://stackoverflow.com/questions/20619488
复制相似问题