如何在 node.js 中安全地将本地文件路径转换为 ​​file::?/url? [英] How to convert local file path to a file::?/ url safely in node.js?

查看:228
本文介绍了如何在 node.js 中安全地将本地文件路径转换为 ​​file::?/url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have local file paths (in node.js) and I need to convert them into file:// urls.

我现在正在查看 https://en.wikipedia.org/wiki/File_URI_scheme 我觉得这一定是一个已解决的问题,必须有人有一个片段或 npm 模块来做到这一点.

I'm now looking at https://en.wikipedia.org/wiki/File_URI_scheme and I feel this must be a solved problem and somebody must have a snippet or npm module to do this.

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

But then I try to search npm for this but I get so much cruft it is not funny (file, url and path are a search hit in like every package ever :) Same with google and SO.

我可以做到这种天真的方法

I can do this naïve approach

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

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

But I'm pretty sure that is not the way to go.

推荐答案

使用 file-url 模块.

Use the 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.并且代码很简单,以防你只想取一个片段:

Also works in Windows. And the code is simple enough, in case you want to just take a snippet:

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 中安全地将本地文件路径转换为 ​​file::?/url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆