forked from postcss/postcss-url
/
get-file.js
75 lines (66 loc) · 1.61 KB
/
get-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
65
66
67
68
69
70
71
72
73
74
75
'use strict';
const fs = require('fs');
const mime = require('mime');
const getPathByBasePath = require('./paths').getPathByBasePath;
const readFileAsync = (filePath) => {
return new Promise((resolse, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
};
const existFileAsync = (filePath) => {
new Promise((resolve, reject) =>
fs.access(filePath, (err) => {
if (err) {
reject();
}
resolve(path);
})
)
};
const oneSuccess = (promises) => {
return Promise.all(promises.map(p => {
return p.then(
val => Promise.reject(val),
err => Promise.resolve(err)
);
})).then(
errors => Promise.reject(errors),
val => Promise.resolve(val)
);
}
/**
*
* @param {PostcssUrl~Asset} asset
* @param {PostcssUrl~Options} options
* @param {PostcssUrl~Dir} dir
* @param {Function} warn
* @returns {Promise<PostcssUrl~File | Undefined>}
*/
const getFile = (asset, options, dir, warn) => {
const paths = options.basePath ?
getPathByBasePath(options.basePath, dir.from, asset.pathname) :
[asset.absolutePath];
return oneSuccess(paths.map(path => existFileAsync(path)))
.then(path => readFileAsync(path))
.then(contents => ({
path: filePath,
contents: contents,
mimeType: mime.getType(filePath)
}))
.catch(() => {
warn(`Can't read file '${paths.join()}', ignoring`);
return;
});
};
module.exports = getFile;
/**
* @typedef {Object} PostcssUrl~File
* @property {String} path
* @property {Buffer} contents
* @property {String} mimeType
*/