/
file.js
75 lines (69 loc) Β· 1.66 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
65
66
67
68
69
70
71
72
73
74
75
'use strict'
const debug = require('debug')('lint-staged:file')
const fs = require('fs').promises
/**
* Check if a file exists. Returns the filename if exists.
* @param {String} filename
* @returns {String|Boolean}
*/
const exists = async filename => {
try {
await fs.access(filename)
return filename
} catch {
return false
}
}
/**
* Read contents of a file to buffer
* @param {String} filename
* @param {Boolean} [ignoreENOENT=true] β Whether to throw if the file doesn't exist
* @returns {Promise<Buffer>}
*/
const readFile = async (filename, ignoreENOENT = true) => {
debug('Reading file `%s`', filename)
try {
return await fs.readFile(filename)
} catch (error) {
if (ignoreENOENT && error.code === 'ENOENT') {
debug("File `%s` doesn't exist, ignoring...", filename)
return null // no-op file doesn't exist
} else {
throw error
}
}
}
/**
* Unlink a file if it exists
* @param {String} filename
* @param {Boolean} [ignoreENOENT=true] β Whether to throw if the file doesn't exist
*/
const unlink = async (filename, ignoreENOENT = true) => {
if (filename) {
debug('Unlinking file `%s`', filename)
try {
await fs.unlink(filename)
} catch (error) {
if (ignoreENOENT && error.code === 'ENOENT') {
debug("File `%s` doesn't exist, ignoring...", filename)
} else {
throw error
}
}
}
}
/**
* Write buffer to file
* @param {String} filename
* @param {Buffer} buffer
*/
const writeFile = async (filename, buffer) => {
debug('Writing file `%s`', filename)
await fs.writeFile(filename, buffer)
}
module.exports = {
exists,
readFile,
unlink,
writeFile
}