-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread-file.ts
More file actions
295 lines (285 loc) · 9.44 KB
/
read-file.ts
File metadata and controls
295 lines (285 loc) · 9.44 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/**
* @fileoverview File-content readers — UTF-8 / binary / safe variants
* (sync + async). The `safe*` versions trap errors and return
* `undefined` (or a caller-supplied `defaultValue`) so they fit the
* non-throwing-fallback shape used elsewhere in the lib.
*
* The encoding `null` overload returns a `Buffer`; the default and any
* string encoding return a string. The runtime fast-path normalizes
* encoding once and forwards untouched options to `node:fs`.
*/
import { getAbortSignal } from '../process/abort'
import { getNodeFs } from '../node/fs'
import { BufferIsBuffer } from '../primordials/buffer'
import { normalizeEncoding } from './encoding'
import type { Abortable } from 'node:events'
import type { ObjectEncodingOptions, PathLike } from 'node:fs'
import type { ReadFileOptions, ReadOptions, SafeReadOptions } from './types'
const abortSignal = getAbortSignal()
/**
* Read a file as binary data asynchronously.
* Returns a Buffer without encoding the contents.
* Useful for reading images, archives, or other binary formats.
*
* @param filepath - Path to file
* @param options - Read options (encoding is forced to null for binary)
* @returns Promise resolving to Buffer containing file contents
*
* @example
* ```ts
* // Read an image file
* const imageBuffer = await readFileBinary('./image.png')
*
* // Read with abort signal
* const buffer = await readFileBinary('./data.bin', { signal: abortSignal })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function readFileBinary(
filepath: PathLike,
options?: ReadFileOptions | undefined,
) {
// Don't specify encoding to get a Buffer.
const opts = typeof options === 'string' ? { encoding: options } : options
const fs = getNodeFs()
return await fs.promises.readFile(filepath, {
signal: abortSignal,
...opts,
encoding: undefined,
})
}
/**
* Read a file as binary data synchronously.
* Returns a Buffer without encoding the contents.
* Useful for reading images, archives, or other binary formats.
*
* @param filepath - Path to file
* @param options - Read options (encoding is forced to null for binary)
* @returns Buffer containing file contents
*
* @example
* ```ts
* // Read an image file
* const imageBuffer = readFileBinarySync('./logo.png')
*
* // Read a compressed file
* const gzipData = readFileBinarySync('./archive.gz')
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function readFileBinarySync(
filepath: PathLike,
options?: ReadFileOptions | undefined,
) {
// Don't specify encoding to get a Buffer
const opts = typeof options === 'string' ? { encoding: options } : options
const fs = getNodeFs()
return fs.readFileSync(filepath, {
...opts,
encoding: undefined,
} as ObjectEncodingOptions)
}
/**
* Read a file as UTF-8 text asynchronously.
* Returns a string with the file contents decoded as UTF-8.
* This is the most common way to read text files.
*
* @param filepath - Path to file
* @param options - Read options including encoding and abort signal
* @returns Promise resolving to string containing file contents
*
* @example
* ```ts
* // Read a text file
* const content = await readFileUtf8('./README.md')
*
* // Read with custom encoding
* const content = await readFileUtf8('./data.txt', { encoding: 'utf-8' })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function readFileUtf8(
filepath: PathLike,
options?: ReadFileOptions | undefined,
) {
const opts = typeof options === 'string' ? { encoding: options } : options
const fs = getNodeFs()
return await fs.promises.readFile(filepath, {
signal: abortSignal,
...opts,
encoding: 'utf8',
})
}
/**
* Read a file as UTF-8 text synchronously.
* Returns a string with the file contents decoded as UTF-8.
* This is the most common way to read text files synchronously.
*
* @param filepath - Path to file
* @param options - Read options including encoding
* @returns String containing file contents
*
* @example
* ```ts
* // Read a configuration file
* const config = readFileUtf8Sync('./config.txt')
*
* // Read with custom options
* const data = readFileUtf8Sync('./data.txt', { encoding: 'utf8' })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function readFileUtf8Sync(
filepath: PathLike,
options?: ReadFileOptions | undefined,
) {
const opts = typeof options === 'string' ? { encoding: options } : options
const fs = getNodeFs()
return fs.readFileSync(filepath, {
...opts,
encoding: 'utf8',
} as ObjectEncodingOptions)
}
/**
* Safely read a file asynchronously, returning undefined on error.
* Useful when you want to attempt reading a file without handling errors explicitly.
* Returns undefined for any error (file not found, permission denied, etc.).
* Defaults to UTF-8 encoding, returning a string unless encoding is explicitly set to null.
*
* @param filepath - Path to file
* @param options - Read options including encoding and default value
* @returns Promise resolving to file contents (string by default), or undefined on error
*
* @example
* ```ts
* // Try to read a file as UTF-8 string (default), get undefined if it doesn't exist
* const content = await safeReadFile('./optional-config.txt')
* if (content) {
* console.log('Config found:', content)
* }
*
* // Read with specific encoding
* const data = await safeReadFile('./data.txt', { encoding: 'utf8' })
*
* // Read as Buffer by setting encoding to null
* const buffer = await safeReadFile('./binary.dat', { encoding: null })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function safeReadFile(
filepath: PathLike,
options: SafeReadOptions & { encoding: null },
): Promise<Buffer | undefined>
/*@__NO_SIDE_EFFECTS__*/
export async function safeReadFile(
filepath: PathLike,
options?: SafeReadOptions | undefined,
): Promise<string | undefined>
/*@__NO_SIDE_EFFECTS__*/
export async function safeReadFile(
filepath: PathLike,
options?: SafeReadOptions | undefined,
): Promise<string | Buffer | undefined> {
// string-options vs options-object ternary; both arms tested but
// the string-shortcut form is less common in test paths.
/* c8 ignore next 4 */
const opts =
typeof options === 'string'
? { __proto__: null, encoding: options }
: ({ __proto__: null, ...options } as SafeReadOptions)
const { defaultValue, ...rawReadOpts } = opts as SafeReadOptions
const readOpts = { __proto__: null, ...rawReadOpts } as ReadOptions
const shouldReturnBuffer = readOpts.encoding === null
// null-encoding arm fires only when caller passes encoding: null.
/* c8 ignore next 3 */
const encoding = shouldReturnBuffer
? undefined
: normalizeEncoding(readOpts.encoding)
const fs = getNodeFs()
try {
return await fs.promises.readFile(filepath, {
__proto__: null,
signal: abortSignal,
...readOpts,
encoding,
} as Abortable)
} catch {}
if (defaultValue === undefined) {
return undefined
}
if (shouldReturnBuffer) {
return BufferIsBuffer!(defaultValue) ? defaultValue : undefined
}
return typeof defaultValue === 'string' ? defaultValue : String(defaultValue)
}
/**
* Safely read a file synchronously, returning undefined on error.
* Useful when you want to attempt reading a file without handling errors explicitly.
* Returns undefined for any error (file not found, permission denied, etc.).
* Defaults to UTF-8 encoding, returning a string unless encoding is explicitly set to null.
*
* @param filepath - Path to file
* @param options - Read options including encoding and default value
* @returns File contents (string by default), or undefined on error
*
* @example
* ```ts
* // Try to read a config file as UTF-8 string (default)
* const config = safeReadFileSync('./config.txt')
* if (config) {
* console.log('Config loaded successfully')
* }
*
* // Read with explicit encoding
* const data = safeReadFileSync('./data.txt', { encoding: 'utf8' })
*
* // Read binary file by setting encoding to null
* const buffer = safeReadFileSync('./image.png', { encoding: null })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function safeReadFileSync(
filepath: PathLike,
options: SafeReadOptions & { encoding: null },
): Buffer | undefined
/*@__NO_SIDE_EFFECTS__*/
export function safeReadFileSync(
filepath: PathLike,
options?: SafeReadOptions | undefined,
): string | undefined
/*@__NO_SIDE_EFFECTS__*/
export function safeReadFileSync(
filepath: PathLike,
options?: SafeReadOptions | undefined,
): string | Buffer | undefined {
// string-options vs options-object ternary; both arms tested but
// the string-shortcut form is less common in test paths.
/* c8 ignore next 4 */
const opts =
typeof options === 'string'
? { __proto__: null, encoding: options }
: ({ __proto__: null, ...options } as SafeReadOptions)
const { defaultValue, ...rawReadOpts } = opts as SafeReadOptions
const readOpts = { __proto__: null, ...rawReadOpts } as ReadOptions
const shouldReturnBuffer = readOpts.encoding === null
// null-encoding arm fires only when caller passes encoding: null.
/* c8 ignore next 3 */
const encoding = shouldReturnBuffer
? undefined
: normalizeEncoding(readOpts.encoding)
const fs = getNodeFs()
try {
return fs.readFileSync(filepath, {
__proto__: null,
...readOpts,
encoding,
} as ObjectEncodingOptions)
} catch {}
if (defaultValue === undefined) {
return undefined
}
if (shouldReturnBuffer) {
return BufferIsBuffer!(defaultValue) ? defaultValue : undefined
}
return typeof defaultValue === 'string' ? defaultValue : String(defaultValue)
}