forked from stoplightio/json-schema-ref-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.js
64 lines (59 loc) · 1.98 KB
/
file.js
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
"use strict";
const fs = require("fs");
const { ono } = require("@jsdevtools/ono");
const url = require("../util/url");
const { ResolverError } = require("../util/errors");
module.exports = {
/**
* The order that this resolver will run, in relation to other resolvers.
*
* @type {number}
*/
order: 100,
/**
* Determines whether this resolver can read a given file reference.
* Resolvers that return true will be tried, in order, until one successfully resolves the file.
* Resolvers that return false will not be given a chance to resolve the file.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @returns {boolean}
*/
canRead (file) {
return url.isFileSystemPath(file.url);
},
/**
* Reads the given file and returns its raw contents as a Buffer.
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @returns {Promise<Buffer>}
*/
read (file) {
return new Promise(((resolve, reject) => {
let path;
try {
path = url.toFileSystemPath(file.url);
}
catch (err) {
reject(new ResolverError(ono.uri(err, `Malformed URI: ${file.url}`), file.url));
}
// console.log('Opening file: %s', path);
try {
fs.readFile(path, (err, data) => {
if (err) {
reject(new ResolverError(ono(err, `Error opening file "${path}"`), path));
}
else {
resolve(data);
}
});
}
catch (err) {
reject(new ResolverError(ono(err, `Error opening file "${path}"`), path));
}
}));
}
};