-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (68 loc) · 2.6 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
const {inspect, promisify} = require('util');
const {URL} = require('url');
const inspectWithKind = require('inspect-with-kind');
const isPlainObj = require('is-plain-obj');
const fileUriToPath = require('file-uri-to-path');
const writeFileAtomic = require('write-file-atomic');
const OPTIONS_SPEC = 'Expected the third argument to be a `write-file-atomic` option (plain <Object>) or a valid encoding (<string>)';
const ENCODING_OPTION_SPEC = 'Expected `encoding` option to be a valid encoding (<string>)';
const promisifiedWriteFileAtomic = promisify(writeFileAtomic);
module.exports = async function writeFileAtomically(...args) {
const argLen = args.length;
if (argLen !== 2 && argLen !== 3) {
throw new RangeError(`Expected 2 or 3 arguments (path: <string>, data: <string|Buffer|Uint8Array>[, options: <Object|string>]), but got ${
argLen === 0 ? 'no' : argLen
} arguments.`);
}
if (args[0] instanceof URL) {
args[0].search = '';
args[0] = fileUriToPath(args[0].toString());
} else if (Buffer.isBuffer(args[0])) {
args[0] = args[0].toString();
} else if (typeof args[0] !== 'string') {
throw new TypeError(`Expected a file path (<string|Buffer|URL>) to write data, but got an invalid value ${
inspectWithKind(args[0])
}.`);
}
const options = args[2];
if (typeof options === 'string') {
if (options.length === 0) {
const err = new Error(`${OPTIONS_SPEC}, but got an empty string.`);
err.code = 'ERR_INVALID_ARG_VALUE';
throw err;
} else if (!Buffer.isEncoding(options)) {
const err = new Error(`${OPTIONS_SPEC}, but got an invalid encoding string ${inspect(options)}.`);
err.code = 'ERR_UNKNOWN_ENCODING';
throw err;
}
args[2] = {encoding: options};
} else if (argLen === 3) {
if (!isPlainObj(options)) {
const err = new TypeError(`${OPTIONS_SPEC}, but got ${inspectWithKind(options)}.`);
err.code = 'ERR_INVALID_ARG_TYPE';
throw err;
}
const {encoding} = options;
if (encoding === '') {
const err = new Error(`${ENCODING_OPTION_SPEC}, but got an empty string.`);
err.code = 'ERR_INVALID_OPT_VALUE_ENCODING';
throw err;
}
if (typeof encoding !== 'string') {
const err = new TypeError(`${ENCODING_OPTION_SPEC}, but got a non-string value ${
inspectWithKind(encoding)
}.`);
err.code = 'ERR_INVALID_OPT_VALUE_ENCODING';
throw err;
}
if (!Buffer.isEncoding(encoding)) {
const err = new Error(`Expected \`encoding\` option to be a valid encoding, but got an unknown one ${
inspect(encoding)
}.`);
err.code = 'ERR_INVALID_OPT_VALUE_ENCODING';
throw err;
}
}
return promisifiedWriteFileAtomic(...args);
};