aboutsummaryrefslogtreecommitdiff
path: root/lib/docx/files.js
blob: cb8655c58cde83d8d89ebf4138aeb2e424bbaeb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var fs = require("fs");
var url = require("url");
var os = require("os");
var dirname = require("path").dirname;
var resolvePath = require("path").resolve;
var isAbsolutePath = require('path-is-absolute');

var promises = require("../promises");


exports.Files = Files;
exports.uriToPath = uriToPath;


function Files(options) {
    options = options || {};
    if (!options.externalFileAccess) {
        return {
            read: function(uri) {
                return promises.reject(new Error("could not read external image '" + uri + "', external file access is disabled"));
            }
        };
    }

    var base = options.relativeToFile ? dirname(options.relativeToFile) : null;

    function read(uri, encoding) {
        return resolveUri(uri).then(function(path) {
            return readFile(path, encoding).caught(function(error) {
                var message = "could not open external image: '" + uri + "' (document directory: '" + base + "')\n" + error.message;
                return promises.reject(new Error(message));
            });
        });
    }

    function resolveUri(uri) {
        var path = uriToPath(uri);
        if (isAbsolutePath(path)) {
            return promises.resolve(path);
        } else if (base) {
            return promises.resolve(resolvePath(base, path));
        } else {
            return promises.reject(new Error("could not find external image '" + uri + "', path of input document is unknown"));
        }
    }

    return {
        read: read
    };
}


var readFile = promises.promisify(fs.readFile.bind(fs));


function uriToPath(uriString, platform) {
    if (!platform) {
        platform = os.platform();
    }

    var uri = url.parse(uriString);
    if (isLocalFileUri(uri) || isRelativeUri(uri)) {
        var path = decodeURIComponent(uri.path);
        if (platform === "win32" && /^\/[a-z]:/i.test(path)) {
            return path.slice(1);
        } else {
            return path;
        }
    } else {
        throw new Error("Could not convert URI to path: " + uriString);
    }
}

function isLocalFileUri(uri) {
    return uri.protocol === "file:" && (!uri.host || uri.host === "localhost");
}

function isRelativeUri(uri) {
    return !uri.protocol && !uri.host;
}