-
Notifications
You must be signed in to change notification settings - Fork 224
/
Copy pathutils.js
71 lines (57 loc) · 1.66 KB
/
utils.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
import normalizePath from "normalize-path";
import { PassThrough } from "node:stream";
export function collectStream(source, callback) {
var collection = [];
var size = 0;
source.on("error", callback);
source.on("data", function (chunk) {
collection.push(chunk);
size += chunk.length;
});
source.on("end", function () {
var buf = Buffer.alloc(size);
var offset = 0;
collection.forEach(function (data) {
data.copy(buf, offset);
offset += data.length;
});
callback(null, buf);
});
}
export function dateify(dateish) {
dateish = dateish || new Date();
if (dateish instanceof Date) {
dateish = dateish;
} else if (typeof dateish === "string") {
dateish = new Date(dateish);
} else {
dateish = new Date();
}
return dateish;
}
export function normalizeInputSource(source) {
if (source === null) {
return Buffer.alloc(0);
} else if (typeof source === "string") {
return Buffer.from(source);
} else if (isStream(source)) {
// Always pipe through a PassThrough stream to guarantee pausing the stream if it's already flowing,
// since it will only be processed in a (distant) future iteration of the event loop, and will lose
// data if already flowing now.
return source.pipe(new PassThrough());
}
return source;
}
export function sanitizePath(filepath) {
return normalizePath(filepath, false)
.replace(/^\w+:/, "")
.replace(/^(\.\.\/|\/)+/, "");
}
export function trailingSlashIt(str) {
return str.slice(-1) !== "/" ? str + "/" : str;
}
export function isStream(stream) {
return stream !== null
&& typeof stream === 'object'
&& typeof stream.pipe === 'function';
}