【问题标题】:Change path separator using path module使用路径模块更改路径分隔符
【发布时间】:2013-02-23 13:44:12
【问题描述】:

这是我的代码:

var thisImageName = thisRow["imagename"];
var thisImagePath = path.relative("./public", __dirname + "/public/uploads/" + thisImageName + ".jpg");
console.log(thisImagePath); // returns __dirname\public\uploads\
img.src = thisImagePath.split(path.sep).join("/");

为了得到合适的图像路径,我必须用路径分隔符分割,然后用合适的斜杠加入数组。有谁知道这样做更有效的方法?

【问题讨论】:

    标签: node.js path


    【解决方案1】:

    此外,您始终可以通过专门使用 posix 路径 API 在路径中获取正斜杠:

    var p = path.posix.relative("./public", imagePath);
    

    编辑:此 api 仅适用于 node 0.12 或更高版本。

    【讨论】:

    • 这是最好的答案。 +1
    【解决方案2】:

    John 的回答只会替换 '\' 的第一个实例

    img.src = thisImagePath.replace(new RegExp('\\' + path.sep, 'g'), '/');
    

    将全部替换。

    您可以将“g”标志传递给.replace,但这是non-standard

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2018-04-25
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多