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

 yoyokk99的秋天 发布于 2023-02-10 09:09

我有本地文件路径(在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;
}

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

2 个回答
  • 使用该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);
    };
    

    2023-02-10 09:13 回答
  • 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

    2023-02-10 09:14 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有