【问题标题】:How to convert local file path to a file::?/ url safely in node.js?如何在 node.js 中安全地将本地文件路径转换为 ​​file::?/ url?
【发布时间】:2014-01-04 08:23:17
【问题描述】:

我有本地文件路径(在 node.js 中),我需要将它们转换为 file:// url。

我现在正在查看https://en.wikipedia.org/wiki/File_URI_scheme,我觉得这一定是一个已解决的问题,并且必须有人有一个 sn-p 或 npm 模块来执行此操作。

但是后来我尝试在 npm 中搜索这个,但我得到了这么多的东西,这并不好笑(文件、url 和路径是像每个包一样的搜索命中 :) 与 google 和 SO 相同。

我可以做这种幼稚的方法

site = path.resolve(site);
if (path.sep === '\\') {
    site = site.split(path.sep).join('/');
}
if (!/^file:\/\//g.test(site)) {
    site = 'file:///' + site;
}

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

【问题讨论】:

  • 查看这篇文章以获得可能的解决方案:stackoverflow.com/questions/18341808/…
  • 您找到解决方案了吗?
  • @wumm 不是真的,我只是像上面的评论者那样使用基于正则表达式的替换。

标签: javascript node.js url npm


【解决方案1】:

使用file-url module

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。而且代码很简单,万一你只想拿个sn-p:

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);
};

【讨论】:

  • 谢谢,这是我发布问题时一直在寻找的内容,我会为后代接受它。
  • 从 file-url 版本 4.0.0 开始,开发者需要 ESM、Node.js 12.0.0+ 并且不再支持 CommonJS(如果您尝试使用 require 会引发错误)。 3.0.0 版仍然有效,但 4.0.0 版施加了许多开发人员可能无法接受的这些限制。我将检查 url 模块和 pathToFileURL() 方法。
【解决方案2】:

我有一个类似的issue,但最终解决方案是使用新的WHATWG URL 实现:

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

【讨论】:

  • 如果路径包含?#% 中的任何一个,这可能会崩溃。
【解决方案3】:

Node.js v10.12.0 刚刚有了两个新方法来解决这个问题:

const url = require('url');
url.fileURLToPath(url)
url.pathToFileURL(path)

文档

【讨论】:

  • 它说:“添加于:v10.12.0”。
  • 谢谢。我修正了我的答案。
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 2013-09-09
  • 2011-01-19
  • 1970-01-01
  • 2014-05-22
  • 2011-02-15
相关资源
最近更新 更多