|
2 | 2 | import fs from 'node:fs';
|
3 | 3 | import path from 'node:path';
|
4 | 4 |
|
5 |
| -const isFileAnEmail = (fullPath: string): boolean => { |
6 |
| - const stat = fs.statSync(fullPath); |
| 5 | +const isFileAnEmail = async (fullPath: string): Promise<boolean> => { |
| 6 | + let fileHandle: fs.promises.FileHandle; |
| 7 | + try { |
| 8 | + fileHandle = await fs.promises.open(fullPath, 'r'); |
| 9 | + } catch (exception) { |
| 10 | + console.warn(exception); |
| 11 | + return false; |
| 12 | + } |
| 13 | + const stat = await fileHandle.stat(); |
7 | 14 |
|
8 |
| - if (stat.isDirectory()) return false; |
| 15 | + if (stat.isDirectory()) { |
| 16 | + await fileHandle.close(); |
| 17 | + return false; |
| 18 | + } |
9 | 19 |
|
10 | 20 | const { ext } = path.parse(fullPath);
|
11 | 21 |
|
12 |
| - if (!['.js', '.tsx', '.jsx'].includes(ext)) return false; |
13 |
| - |
14 |
| - // This is to avoid a possible race condition where the file doesn't exist anymore |
15 |
| - // once we are checking if it is an actual email, this could cause issues that |
16 |
| - // would be very hard to debug and find out the why of it happening. |
17 |
| - if (!fs.existsSync(fullPath)) { |
| 22 | + if (!['.js', '.tsx', '.jsx'].includes(ext)) { |
| 23 | + await fileHandle.close(); |
18 | 24 | return false;
|
19 | 25 | }
|
20 | 26 |
|
21 | 27 | // check with a heuristic to see if the file has at least
|
22 | 28 | // a default export (ES6) or module.exports (CommonJS) or named exports (MDX)
|
23 |
| - const fileContents = fs.readFileSync(fullPath, 'utf8'); |
| 29 | + const fileContents = await fileHandle.readFile('utf8'); |
| 30 | + |
| 31 | + await fileHandle.close(); |
24 | 32 |
|
25 | 33 | // Check for ES6 export default syntax
|
26 | 34 | const hasES6DefaultExport = /\bexport\s+default\b/gm.test(fileContents);
|
@@ -80,10 +88,13 @@ export const getEmailsDirectoryMetadata = async (
|
80 | 88 | withFileTypes: true,
|
81 | 89 | });
|
82 | 90 |
|
83 |
| - const emailFilenames = dirents |
84 |
| - .filter((dirent) => |
| 91 | + const isEmailPredicates = await Promise.all( |
| 92 | + dirents.map((dirent) => |
85 | 93 | isFileAnEmail(path.join(absolutePathToEmailsDirectory, dirent.name)),
|
86 |
| - ) |
| 94 | + ), |
| 95 | + ); |
| 96 | + const emailFilenames = dirents |
| 97 | + .filter((_, i) => isEmailPredicates[i]) |
87 | 98 | .map((dirent) =>
|
88 | 99 | keepFileExtensions
|
89 | 100 | ? dirent.name
|
|
0 commit comments