如何在node.js中安全地将本地文件路径转换为文件::?/ url?

Bar*_*vds 12 javascript url node.js npm

我有本地文件路径(在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;
}
Run Code Online (Sandbox Code Playgroud)

但我很确定这不是要走的路.

Cam*_*tin 20

使用该file-url模块.

npm install --save file-url
Run Code Online (Sandbox Code Playgroud)

用法:

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
Run Code Online (Sandbox Code Playgroud)

也适用于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);
};
Run Code Online (Sandbox Code Playgroud)


HaN*_*riX 8

Node.js v10.12.0仅提供了两种新方法来解决此问题:

const url = require('url');
url.fileURLToPath(url)
url.pathToFileURL(path)
Run Code Online (Sandbox Code Playgroud)

文献资料


Ale*_*ske 5

我遇到了类似的问题,但解决方案最终是使用新的WHATWG URL实现:

const path = 'c:\\Users\\myname\\test.swf';
const u = new URL(`file:///${path}`).href;
// u = 'file:///c:/Users/myname/test.swf'
Run Code Online (Sandbox Code Playgroud)

  • 如果路径包含“?”、“#”或“%”中的任何一个,这可能会失败。 (2认同)