-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileutil.js
62 lines (51 loc) · 1.69 KB
/
fileutil.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
const fs = require('fs');
const inquirer = require('inquirer');
const path = require('path');
async function promptDestinationPath() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'destinationPath',
message: 'Enter the destination path:',
default: './', // Set a default value or leave it empty based on your preference
},
]);
return answers.destinationPath;
}
async function saveFilesFromURL(matchingFiles, destinationPath) {
// Create destination directory if it doesn't exist
fs.mkdirSync(destinationPath, { recursive: true });
for (const file of matchingFiles) {
const decodedContent = await getFileContent(file.download_url);
await saveFile(decodedContent, file.name, destinationPath);
}
}
async function saveFile(decodedContent, fileName, destinationPath) {
const filePath = `${destinationPath}/${fileName}`;
console.log(`Saving ${fileName} to ${filePath}`);
fs.mkdirSync(destinationPath, { recursive: true });
try {
fs.writeFileSync(path.resolve(filePath), decodedContent, { encoding: 'utf8', flag:'a+' });
console.log(`${fileName} saved successfully.`);
} catch (error) {
console.error(`Error saving ${fileName}: ${error.message}`);
}
}
async function getFileContent(download_url) {
try {
const fileContent = await fetch(download_url, {
method: 'GET',
}
);
return fileContent.text();
}
catch (error) {
throw new Error(`Error fetching file content: ${error.message}`);
}
}
module.exports = {
promptDestinationPath,
saveFilesFromURL,
getFileContent,
saveFile
}