UNPKG

2.53 kBJavaScriptView Raw
1/**
2 * @fileoverview Common helpers for operations on filenames and paths
3 * @author Ian VanSchooten
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const path = require("path");
12
13//------------------------------------------------------------------------------
14// Private
15//------------------------------------------------------------------------------
16
17/**
18 * Replace Windows with posix style paths
19 *
20 * @param {string} filepath Path to convert
21 * @returns {string} Converted filepath
22 */
23function convertPathToPosix(filepath) {
24 const normalizedFilepath = path.normalize(filepath);
25 const posixFilepath = normalizedFilepath.replace(/\\/g, "/");
26
27 return posixFilepath;
28}
29
30/**
31 * Converts an absolute filepath to a relative path from a given base path
32 *
33 * For example, if the filepath is `/my/awesome/project/foo.bar`,
34 * and the base directory is `/my/awesome/project/`,
35 * then this function should return `foo.bar`.
36 *
37 * path.relative() does something similar, but it requires a baseDir (`from` argument).
38 * This function makes it optional and just removes a leading slash if the baseDir is not given.
39 *
40 * It does not take into account symlinks (for now).
41 *
42 * @param {string} filepath Path to convert to relative path. If already relative,
43 * it will be assumed to be relative to process.cwd(),
44 * converted to absolute, and then processed.
45 * @param {string} [baseDir] Absolute base directory to resolve the filepath from.
46 * If not provided, all this function will do is remove
47 * a leading slash.
48 * @returns {string} Relative filepath
49 */
50function getRelativePath(filepath, baseDir) {
51 let relativePath;
52
53 if (!path.isAbsolute(filepath)) {
54 filepath = path.resolve(filepath);
55 }
56 if (baseDir) {
57 if (!path.isAbsolute(baseDir)) {
58 throw new Error("baseDir should be an absolute path");
59 }
60 relativePath = path.relative(baseDir, filepath);
61 } else {
62 relativePath = filepath.replace(/^\//, "");
63 }
64 return relativePath;
65}
66
67//------------------------------------------------------------------------------
68// Public Interface
69//------------------------------------------------------------------------------
70
71module.exports = {
72 convertPathToPosix,
73 getRelativePath
74};