Skip to content

Commit 1216843

Browse files
committed
Ensure target directory exists before copying files
Refactor the code to add a new function `ensureDirectoryExists` that checks and creates the target directory if it doesn't exist. This ensures that the directory is always present when copying files, thus preventing potential errors.
1 parent 1ad937b commit 1216843

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

copy-static-files.js

+9-4
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,20 @@ const path = require('node:path');
44
const staticDir = path.join(__dirname, 'static');
55
const distDir = path.join(__dirname, 'dist');
66

7-
async function copyFiles(sourceDir, targetDir) {
7+
async function ensureDirectoryExists(directory) {
88
try {
9-
await fs.access(targetDir);
9+
await fs.access(directory);
1010
} catch (error) {
11-
console.error(`Error: The target directory '${targetDir}' does not exist`);
12-
process.exit(1);
11+
console.info(`Directory '${directory}' does not exist, creating it...`);
12+
await fs.mkdir(directory, { recursive: true });
13+
console.info(`Directory '${directory}' created successfully.`);
1314
}
15+
}
1416

17+
async function copyFiles(sourceDir, targetDir) {
1518
try {
19+
await ensureDirectoryExists(targetDir);
20+
1621
const files = await fs.readdir(sourceDir);
1722

1823
await Promise.all(files.map(async (file) => {

0 commit comments

Comments
 (0)